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
.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With