Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and replace strings in vim on multiple lines

Tags:

vim

vi

I can do :%s/<search_string>/<replace_string>/g for replacing a string across a file, or :s/<search_string>/<replace_string>/ to replace in current line.

How can I select and replace words from selective lines in vim?

Example: replace text from lines 6-10, 14-18 but not from 11-13.

like image 728
Anshul Goyal Avatar asked Nov 15 '13 06:11

Anshul Goyal


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 select multiple lines in vi?

Manipulate multiple lines of textPlace your cursor anywhere on the first or last line of the text you want to manipulate. Press Shift+V to enter line mode. The words VISUAL LINE will appear at the bottom of the screen. Use navigation commands, such as the Arrow keys, to highlight multiple lines of text.


2 Answers

Replace All:

:%s/foo/bar/g 

Find each occurrence of 'foo' (in all lines), and replace it with 'bar'.

For specific lines:

:6,10s/foo/bar/g 

Change each 'foo' to 'bar' for all lines from line 6 to line 10 inclusive.

like image 159
Jayanth Ramachandran Avatar answered Sep 29 '22 19:09

Jayanth Ramachandran


The :&& command repeats the last substitution with the same flags. You can supply the additional range(s) to it (and concatenate as many as you like):

:6,10s/<search_string>/<replace_string>/g | 14,18&& 

If you have many ranges though, I'd rather use a loop:

:for range in split('6,10 14,18')| exe range 's/<search_string>/<replace_string>/g' | endfor 
like image 36
Ingo Karkat Avatar answered Sep 29 '22 18:09

Ingo Karkat