Tuesday, December 13, 2011

Using vim editor to find and replace effectively

Taken from this excellent article Vi and Vim Editor: 12 Powerful Find and Replace Examples

Here is a few examples that I love to use. You can see that this entry is a notepad for me.

Scenario 1: Replace all occurrences of a text with another text in the whole file
:%s/old-text/new-text/g
%s - specifies all lines. Specifying the range as ‘%’ means do substitution in the entire file.
g flag– specifies all occurrences in the line. With the ‘g’ flag , you can make the whole line to be substituted. If this ‘g’ flag is not used then only first occurrence in the line only will be substituted.

 Scenario 2: Replace of a text with another text within a range of lines
:1,10s/old-text/new-text/gi
1-10 - Do substitution from line 1 to 10
i flag - Make the substitute search text to be case insensitive.


Scenario 3:  Replacing of a text with another text for a the 1st X number of lines
From the current position of the cursor, the command will replace according to the number of count. For example, do substitution in 10 lines from the current line.
:s/old-text/new-text/g 10

Scenario 4: Substitute only the whole word and not partial match
If you wish to change the whole word "text" to "new-text"
Original Text: old to text
:s/\<text\>/new-text/
Translated Text: old to new-text


No comments: