Powerful Find and Replace Examples For VI Editor – Part 1
Syntax of the text substitution inside vim editor:
:[range]s[ubstitute]/{pattern}/{string}/[flags] [count]
Following are three possible flags.
- [c] Confirm each substitution.
- [g] Replace all occurrences in the line.
- [i] Ignore case for the pattern.
Substitute all occurrences of a text with another text in the whole file
This is the basic fundamental usage of the text substitution inside Vi editor. When you want a specific text to be replaced with another text in the entire file then you can use the following sequence.
:%s/old-text/new-text/g
%s – specifies all lines. Specifying the range as ‘%’ means do substitution in the entire file.
g – specifies all occurrences in the line. With the ‘g’ flag , you can make the whole line to be substituted. If this ‘g’ flag is not used then only first occurrence in the line only will be substituted.
Substitution of a text with another text within a single line
When you want a specific text to be replaced with another text within a single line in a case insensitive manner. Specifying no range means, do substitution in the current line only. With the ‘i’ flag, you can make the substitute search text to be case insensitive.
:s/I/We/gi
Substitution of a text with another text within a range of lines
With the range, you can make only a range of line to be affected in the substitution. Specifying 1, 10 as range means, do substitution only in the lines 1 – 10.
:1,10s/helo/hello/g
Substitution of a text with another text by visual selection of lines
You can also select a specific lines by visually selecting those lines. Press CTRL + V in command mode, use navigation keys to select the part of the file you want to be substituted. Press ‘:’ which will automatically formed as :’<,’> Then you can use the normal substitute as
:'<,'>s/helo/hello/g
Substitution of a text with another text only the 1st X number of lines
Using count in substitution, If you specify the count N in the substitution then it means do substitution in N lines from the current position of the cursor. do substitution in 4 lines from the current line.
:s/helo/hello/g 4
Substitute only the whole word and not partial match
Let us assume that you want to change only the whole word ‘his’ to ‘her’ in the original text mentioned below. If you do the standard substitution, apart from changing his to her, it will also change This to Ther as shown below.
Standard Subsitution
Original Text: This is his idea :s/his/her/g Translated Text: Ther is her idea
Whole Word Subsitution
Original Text: This is his idea :s/\<his\>/her/ Translated Text: This is her idea
Note: You should enclose the word with < and > , which will force the substitution to search only for the full word and not any partial match