Vim, Vi Search Find And Replace Texts
Vim is a powerful tool for text editing code developments etc. One of the most wanted and loved feature is find and replace simple substitute. We will look different ways to find and replace operation in vim. Our text file named file1 is like below.
This is line 1
We can resume
Change the station
Simply Replace with Vim
To work with replace function we need to open text file with vim and then run replace command.
- %s will look all lines for /line occurrence
- /LINE will be replaced with /g flag.
Replace In Single Line
If we want to replace only in single line not in the whole file we will remove % from command like below. We will change LINE to the line
Ask For Confirmation
We can confirm the changes one by one while changing them with the command below.
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 with spaces.
Specify Replace Range
We can specify search range by providing line numbers. Substitution will occur only in the range of this numbers.
There will be no substitution because we have specified lines between 2 and 3 where there is no search result for LINE
We can search incasesensitively and then replace with the following command.