Vim is a powerful tool for text editing code developments etc. One of the most wanted and loved features is to find and replace a simple substitute. We will look at different ways to find and replace operation in vim. Our text file named file1
is like below.
This is line 1 We can resume Extra file Change the station
Simply Replace with Vim
To work with replace function we need to open the text file with vim and then run replace command.
:%s/line/LINE/g

- %s will look at all lines for /line occurrence
- /LINE will be replaced with /g flag.
Replace In Single Line
If we want to replace only in a single line, not in the whole file we will remove % from command like below. We will change LINE to the line
:s/LINE/line/g

Ask For Confirmation
We can confirm the changes one by one while changing them with the command below. We will use %s
option and provide the original text and new text. After that, we will provide /gc
to the end of the expression.
:%s/line/LINE/gc

Replace Only Whole Words
To prevent errors like not word change we can specify to change only the whole words.
:%s/ \LINE\ /line/g

We have only changed the word LINE which is surrounded by spaces.
Specify Replace Range
We can specify the search range by providing line numbers. The substitution will occur only in the range of these numbers.
:2,3s/LINE/line/g

There will be no substitution because we have specified lines between 2 and 3 where there is no search result for LINE
Search Caseinsentive
We can search insensitive and then replace it with the following command.
:%s/Line/LINE/gi
