DEV Community

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

Posted on Edited 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
🔴 Hot News: voyegr/magic with vim global command hj - Kapook Update 2025 🔴 Hot News: voyegr/magic with vim global command hj - Kapook Update 2025

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

:g/\<dog\>/ .w! >> dog.txt | d
🔴 Hot News: voyegr/magic with vim global command hj - Kapook Update 2025 🔴 Hot News: voyegr/magic with vim global command hj - Kapook Update 2025

Copy lines with a pattern to a register

First let's clean the register we want to use

:let @a=''
🔴 Hot News: voyegr/magic with vim global command hj - Kapook Update 2025 🔴 Hot News: voyegr/magic with vim global command hj - Kapook Update 2025

Now we can copy the lines with a pattern to it

:g/pattern/y A
:g/pattern/ .,+5 y A 
🔴 Hot News: voyegr/magic with vim global command hj - Kapook Update 2025 🔴 Hot News: voyegr/magic with vim global command hj - Kapook Update 2025

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
🔴 Hot News: voyegr/magic with vim global command hj - Kapook Update 2025 🔴 Hot News: voyegr/magic with vim global command hj - Kapook Update 2025

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
🔴 Hot News: voyegr/magic with vim global command hj - Kapook Update 2025 🔴 Hot News: voyegr/magic with vim global command hj - Kapook Update 2025

Top comments (0)