Find and replace in Vi or vim editor

In this article, we will see Find and replace in Vi or vim editor with examples. IN Vim or vi, we can easily find and replace text using :s(:substitute) command. We can run this command only in normal mode. To go back to normal mode just press on ESC key from your keyboard. Find and replace operation is case-sensitive which means “R2schools” and “r2schools” are not same.

Syntax to Find and Replace in Vi or Vim editor:

:[range]s/{pattern}/{string}/[flags] [count]

Examples to Find and replace in Vi or vim editor:

1. Find the word ‘db’ and replace with “database” from the file r2schools.org. Following find 1st occurrence of file and replaces. After typing the command press enter.

vi r2schools.org

:s/db/database/

2. Find the word ‘db’ and replace with “database” from the file r2schools.org. Following syntax finds all occurrences in a line of file and replaces. But, not entire file. g means entire line(global)

vi r2schools.org

:s/db/database/g

3. Find the word ‘db’ and replace with “database” from the file r2schools.org. Following syntax finds all occurrences of file and replaces. It finds and replaces all occurrences of a file.

vi r2schools.org

:%s/db/database/g

4. To ignore case-sensitiv, use i at the end like below.

vi r2schools.org

:%s/db/database/gi

5. If we want to search for range of lines, we have to use starting line and ending line numbers. Following example searches only from line number 2 and line number 6. If it finds match then replaces with database.

:2,6s/db/database/gi

6. If we want to comment lines from 2,5 with #(hash) use the following command in Linux.

:2,5s/^/#/

In the same way, if we want to uncomment lines from 2 to 5.

:2,5s/^#//

7. Remove trailing spaces at the end of each line in Linux using vi editor, run the following command.

%s/\s\+$//e