DEV Community

Sérgio Araújo
Sérgio Araújo

Posted on Edited on

Avoiding manual copy of infromation with vim

Introduction

For many times we need copy information from and to the system clipboard. For those situations, we can use a simple grep plus (pbcopy | xclip), but if you are with the file already open, or if you are in a system wich does not have GNU utils you can do the task simply using vim

The problem

Let's say you have to copy all lines of code with a specific pattern from all your opened files on vim:

vim * text.txt
✨ อัปเดตล่าสุด: voyegr/avoiding manual copy of infromation with vim k - Kapook Update 2025 ✨ อัปเดตล่าสุด: voyegr/avoiding manual copy of infromation with vim k - Kapook Update 2025

With the :args command we can see the list of all opened files we have.

:args
✨ อัปเดตล่าสุด: voyegr/avoiding manual copy of infromation with vim k - Kapook Update 2025 ✨ อัปเดตล่าสุด: voyegr/avoiding manual copy of infromation with vim k - Kapook Update 2025

The solution

We are gonna start cleaning the targed register, a kind of many vim "clipboards" that accept appending with a special thecnique.

:let @a=""
✨ อัปเดตล่าสุด: voyegr/avoiding manual copy of infromation with vim k - Kapook Update 2025 ✨ อัปเดตล่าสุด: voyegr/avoiding manual copy of infromation with vim k - Kapook Update 2025

With the above command we are making sure the register a is empty

:argdo g/pattern/yank A
✨ อัปเดตล่าสุด: voyegr/avoiding manual copy of infromation with vim k - Kapook Update 2025 ✨ อัปเดตล่าสุด: voyegr/avoiding manual copy of infromation with vim k - Kapook Update 2025

The argdo command performs a task over all opened files we have, and the magic happens with the global command. OBS: the use of A allows us to append every line of all files containing the pattern to the register a.

Now let's finish:

:let @+=@a
✨ อัปเดตล่าสุด: voyegr/avoiding manual copy of infromation with vim k - Kapook Update 2025 ✨ อัปเดตล่าสุด: voyegr/avoiding manual copy of infromation with vim k - Kapook Update 2025

OBS: If you simply try to use :argdo g/pattern/yank + will not work because the system clipboard does not allow "appending" any content to it.

How would it be like using grep?

grep 'pattern' *.txt | xclip -selection clipboard
✨ อัปเดตล่าสุด: voyegr/avoiding manual copy of infromation with vim k - Kapook Update 2025 ✨ อัปเดตล่าสุด: voyegr/avoiding manual copy of infromation with vim k - Kapook Update 2025

Creating aliases in order to make it easier

In my case I use zsh and on my aliases file I have

(( $+commands[xclip] )) && {
    alias pbpaste='xclip -i -selection clipboard -o'
    alias pbcopy='xclip -selection clipboard'
}
✨ อัปเดตล่าสุด: voyegr/avoiding manual copy of infromation with vim k - Kapook Update 2025 ✨ อัปเดตล่าสุด: voyegr/avoiding manual copy of infromation with vim k - Kapook Update 2025

Top comments (0)