Format
The format of the command is given below:
%s/<string_being_replaced>/<replacement_string>/
Examples
In order to replace the word “hate” with “love”.
- Open the file in vi
- Hit [Esc] (Esc in vi lets you type commands instead of typing content)
- Type : (colon) followed by %s/hate/love/ and hit [Enter] key.
:%s/hate/love/
Above command will replace first occurrence of word hate with love on all lines. The % represents all lines.
To replace all occurrences of word hate with love on all lines, use the g option (g stands for global, indicating all occurrences).
:%s/hate/love/g
You can replace g with a number 1,2,…N to change only the n’th occurrence on each line.
Use find and replace on line ranges (match by line numbers)
You can also make changes on range of lines i.e. replace first occurrence of hate with love on lines 5 through 20 only, enter:
:5,20s/hate/love/
Following command will replace first occurrence of hate with love starting at the current line for the next 100 lines:
:.,+100s/hate/love/
Word Match
You can match by words i.e. find the next line containing a word “test”, then replace all occurrences of hate with love:
:/test/s/hate/love/g
To specify ranges:
:/test/,/guest/s/hate/love/g
Leave a comment