How do I chain multiple commands on lines matching a pattern with :g?
Answer
:g/pattern/cmd1 | cmd2
Explanation
The :g (global) command can execute multiple Ex commands per matching line by chaining them with |. This lets you perform complex multi-step operations on every line that matches your pattern.
How it works
" For each line matching 'pattern', run cmd1 then cmd2
:g/pattern/cmd1 | cmd2
Examples
" Delete lines matching pattern and echo a count
:let c=0 | g/DEBUG/d | let c+=1
" Comment out and indent matching lines
:g/TODO/s/^/\/\/ / | >
" Copy matching lines to end of file and uppercase them
:g/^func /t$ | $ normal gUU
" Center and add decoration to headings
:g/^# /center 80 | s/$/ =====/
Using :execute for complex operations
" Run different commands based on the match
:g/error/execute 'normal! I[ERROR] ' | s/$/;/
" Use line numbers dynamically
:g/pattern/execute 'normal! A // line ' . line('.')
Global with ranges
" Operate on matching lines plus context
:g/pattern/.,+3 s/old/new/g
" Delete matching lines and the 2 lines below them
:g/pattern/.,+2d
" Indent matching lines and their block
:g/^if/.,/^endif/ >
Tips
- Each
|creates a new command in the chain, not a pipe :gprocesses lines top-to-bottom; deleting lines can shift line numbers- Use
:g/pattern/commandwith:v/pattern/command(inverse) for complementary operations :gaccepts any Ex command —:s,:d,:m,:t,:normal,:execute, etc.- This is one of the most powerful features inherited from
ed— the original Unix editor - Documented under
:help :global