How to search and replace globally, starting from the cursor position and wrapping around the end of file, in a single command invocation in Vim?

basteln picture basteln · Sep 29, 2011 · Viewed 61.1k times · Source

When I search with the / Normal-mode command:

/\vSEARCHTERM

Vim starts the search from the cursor position and continues downwards, wrapping around to the top. However, when I search and replace using the :substitute command:

:%s/\vBEFORE/AFTER/gc

Vim starts at the top of the file, instead.

Is there a way to make Vim perform search and replace starting from the cursor position and wrapping around to the top once it reaches the end?

Answer

Peter Rincker picture Peter Rincker · Sep 29, 2011

You are already using a range, %, which is short hand for 1,$ meaning the entire file. To go from the current line to the end you use .,$. The period means current line and $ means the last line. So the command would be:

:.,$s/\vBEFORE/AFTER/gc

But the . or current line can be assumed therefore can be removed:

:,$s/\vBEFORE/AFTER/gc

For more help see

:h range