Vim, Vi Search Find And Replace Texts Tutorial with Examples – POFTUT

Vim, Vi Search Find And Replace Texts Tutorial with Examples

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.

Simply Replace
  • %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

Replace In Single Line

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.

Ask For Confirmation

Replace Only Whole Words

To prevent errors like not word change we can specify to change only the whole words.

:%s/ \LINE\ /line/g
Replace Only Whole Words

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.

Specify Replace Range

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.

Search Incasesentive
Search Incasesentive

LEARN MORE  Vi and Vim Search and Replace Operations

Leave a Comment