DEV Community

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

Posted on • Updated on

Magic with vim global command

Intro

The vim global command is a very powerful command, of course
in the comments sections many more will appear, just to give you
an idea on how useful it can be let's look to some situations.

create a new file based on a global pattern

Let's say we have this file:

this line contains cat
this contains dog
other nothing
more one with fish
this line contains cat
this contains dog
Enter fullscreen mode Exit fullscreen mode

And we want a new file with the lines containing "dog" and delete them from the original file.

:g/\<dog\>/ .w! >> dog.txt | d
Enter fullscreen mode Exit fullscreen mode

Copy lines with a pattern to a register

First let's clean the register we want to use

:let @a=''
Enter fullscreen mode Exit fullscreen mode

Now we can copy the lines with a pattern to it

:g/pattern/y A
:g/pattern/ .,+5 y A 
Enter fullscreen mode Exit fullscreen mode

The uppercase version of the register allow us to append content to a register, otherwise it will be overwrited.

To paste a register just

:0 put a
Enter fullscreen mode Exit fullscreen mode

The above command says: at the line zero put the content of the register 'a'

" move TITLE down one line
:g/TITLE/ m+1   

" copy 'pattern' to <line number>
:g/pattern/t<line number> 

" erase even lines
:g/^/if line('.') % 2 == 0 | norm! cc

" erase odd lines
:g/^/if line('.') % 2 | normal! cc

" add a line before a pattern
:g/^wget/ normal O
Enter fullscreen mode Exit fullscreen mode

Top comments (0)