DEV Community

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

Posted on • Updated 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
Enter fullscreen mode Exit fullscreen mode

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

:args
Enter fullscreen mode Exit fullscreen mode

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=""
Enter fullscreen mode Exit fullscreen mode

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

:argdo g/pattern/yank A
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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'
}
Enter fullscreen mode Exit fullscreen mode

Latest comments (0)