Thursday, 11 April 2013

Find And Replace Text with VI


Both vi and vim text editor comes with substitute command for finding and replacing text.

Syntax

:%s/WORD-To-Find-HERE/Replace-Word-Here/g
OR
:%s/FindMe/ReplaceME/g

Examples

The substitute command can be used as per your requirements.

VI / Vim Basic Find and Replace

To find each occurrence of 'UNIX', and replace it with 'Linux', enter (press ESC, type : and following command)::%s/UNIX/Linux/g

Find and Replace with Confirmation

Find a word called 'UNIX' and replace with 'Linux', but ask for confirmation first, enter:
:%s/UNIX/Linux/gc

Find and Replace Whole Word Only

Find whole words exactly matching 'UNIX' to 'Linux'; and ask for confirmation too:
:%s/\<UNIX\>/Linux/gc

Case Insensitive Find and Replace

Find 'UNIX' (match UNIX, unix, UnIx, Unix and so on) and replace with 'Linux':
:%s/unix/Linux/gi
Same command with confirmation:
:%s/unix/Linux/gic

Case sensitive Find and Replace

Find each 'UNIX' and replace with 'bar':
:%s/UNIX/bar/gI
Same command with confirmation:
:%s/UNIX/bar/gIc

Replace In the Current Line Only

Find 'UNIX' and replace with 'Linux' in the current line only (note % is removed from substitute command):
:s/UNIX/Linux/g
NOTE: You need to prefix % the substitute command to make changes on all lines:
:%s/UNIX/Linux/g

Replace All Lines Between line 100 and line 250

:{START-n},{END-n}s/word1/word2/g
Find 'UNIX' and replace with 'Linux' all lines between line 100 and line 250, enter:
:100,200s/UNIX/Linux/g
OR
:100,200s/UNIX/Linux/gc

No comments:

Post a Comment