vi Editor Find And Replace String Commands

Syntax:

:%s/Search String/Replace String/g

Examples

Fundamental Find and Replace

Replace MYSQL with ORACLE

:%s/MYSQL/ORACLE/g

Find and Replace with Confirmation

:%s/MYSQL/Oracle/gc

Case sensitive Find and Replace

:%s/MYSQL/oracle/gI

Case Insensitive Find and Replace

:%s/mysql/Oracle/gi

Find and Replace In the Current Line Only

:s/MYSQL/Oracle/g

Current line is the line where cursor is located

Find and Replace Between Specific Line

:{START-n},{END-n}s/word1/word2/g

Example, find and replace between 100 and 150 line

:100,150s/MYSQL/Oracle/g

Find and Replace Between Specific Line to Current Line

:1,.s/mysql/oracle/

Current line is the line where cursor is located which can be specified as a single dot (.).

Find and Replace Between Current line to Last Line

:,,$s/mysql/oracle/

Current line is the line where cursor is located which can be specified as a single dot (.).

Find and Replace Between Current Line to n Next Line

:.,+ns/mysql/oracle/

Here n is the number of line.

Example:

You want to replace from current to next 10 lines

:.,+10s/mysql/oracle/

Find and Replace Between Current Line to n Above Line

:.,-ns/mysql/oracle/

Here n is the number of line.

Example:

You want to replace from current to above 10 lines.

:.,-10s/mysql/oracle/

Find and Replace with some extra condition

In this example the command will search and replace those line where the line have keyword Oracle

Oracle 4546

Mysql 4546

SAP 4546

DB2 4546

Oracle 4546

Excess 4546

Oracle 4546

:g/Oracle/s/4546/0000/g

After replacing

Oracle 0000

Mysql 4546

SAP 4546

DB2 4546

Oracle 0000

Excess 4546

Oracle 0000

In this example the command will search and replace those line where the line dont have keyword Oracle, this is the opposite of above example.

Oracle 4546

Mysql 4546

SAP 4546

DB2 4546

Oracle 4546

Excess 4546

Oracle 4546

:v/Oracle/s/4546/0000/g

Oracle 4546

Mysql 0000

SAP 0000

DB2 0000

Oracle 4546

Excess 0000

Oracle 4546