Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim's global command with patterns joined by comma

Tags:

command

vim

ex

From the docs, the syntax of the :global command is:

:[range]g[lobal]/{pattern}/[cmd]
                        Execute the Ex command [cmd] (default ":p") on the
                        lines within [range] where {pattern} matches.

I've also come across such usages of :g:

:g/apples/+1,/peaches/ s/^/# /g
:g/start/+1,$ sort n

Does /apples/+1,/peaches/ here belong to the {pattern}? Where is this syntax documented?

like image 388
Eugene Yarmash Avatar asked Mar 02 '26 23:03

Eugene Yarmash


1 Answers

I just found an explanation for this very usage of :global in Vim Tips Wiki:

:g/apples/,/peaches/ s/^/# /g
    Insert "# " at the start of each line in all identified blocks. 
    :g/apples/ identifies each line containing "apples". 
    In each such line, .,/peaches/ s/^/# /g is executed 
    (the . is assumed; it means the current line, where "apples" occurs). 

So ,/peaches/ here defines a range for the substitution command. The somewhat confusing part (which i didn't find mentioned in the docs) is that the initial '.' is optional in a range. Adding it makes the command more obvious:

:g/apples/.,/peaches/s/^/# /g
like image 141
Eugene Yarmash Avatar answered Mar 04 '26 11:03

Eugene Yarmash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!