Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vim search and replace using current line as reference point

Tags:

vim

Is there a way to specify search and replace range using the current line as a reference? I can specify range using explicit line numbers like

:5,15s/foo/bar/g

to do the search and replace on only lines 5 to 15. How to specify a range like "from the current line to 10 lines below (or above) the current line"?

like image 269
EricC Avatar asked Aug 02 '13 15:08

EricC


People also ask

How do I search and replace in Vim?

Basic Find and Replace In Vim, you can find and replace text using the :substitute ( :s ) command. To run commands in Vim, you must be in normal mode, the default mode when starting the editor. To go back to normal mode from any other mode, just press the 'Esc' key.

How do you replace a word with another word in Vim?

Search for text using / or for a word using * . In normal mode, type cgn (change the next search hit) then immediately type the replacement. Press Esc to finish. From normal mode, search for the next occurrence that you want to replace ( n ) and press . to repeat the last change.

How do you jump between lines in Vim?

If we are in the vim editor, then simply do this, “Press the ENTER key, write the Line number, and press Shift+ g”: Again the output is the same.

How do I go to the last line in Vim?

On a character in the first line, press Ctrl-V (or Ctrl-Q if Ctrl-V is paste). Press jj to extend the visual block over three lines. Press $ to extend the visual block to the end of each line.


2 Answers

You can use . for the current position, and .+10 for 10 lines down:

:.,.+10s/foo/bar/g 

Some other useful ranges:

  • % for the whole file. Example: :%s/foo/bar/g.
  • '<,'> for the lines of visually selected block. This might get you more than you want of the visual selection starts or ends in the middle of a line. The whole line is included.
  • 'a,'b from mark a to mark b.
  • .,$ from the current line to the end of the file.
like image 132
Codie CodeMonkey Avatar answered Sep 26 '22 08:09

Codie CodeMonkey


:help :range gives you all the details; you can do quite sophisticated things, e.g. :'a;/pat1/-1.

For ranges starting from the current line, a neat trick is to start command-line mode by prefixing the : with a count: E.g. 5: turns into :.,.+4.

Protip: Learn how to look up commands and navigate the built-in :help; it is comprehensive and offers many tips. You won't learn Vim as fast as other editors, but if you commit to continuous learning, it'll prove a very powerful and efficient editor.

like image 31
Ingo Karkat Avatar answered Sep 23 '22 08:09

Ingo Karkat