Monday, September 2, 2013

Find and Replace in Vi editor

Syntax for Text Substitution inside the vi editor is,

:[range]s[ubstitute]/{pattern}/{string}/[Flags] [count]

Following are the possible Flags

[g] -> replace all occurances in the line.
[c] -> Confirm each substitution
[i] -> make case insensitive

Case 1: Replace a text with another in the whole file

:%s/oldText/newText/g

where %s indicates all lines in the file.

Case 2: Replace a text within a single line

:s/oldText/newText/g

No range was specified therefore it replaces text in the single line.

:s/I/oldText/newText/g

where I indicates case insensitive

Case 3: Replace a text within a range of lines

:1,10s/oldText/newText/g

replaces text between line 1 and 10

Case 4: Replace text in only the first N lines

:s/oldText/newText/g 5

replaces the text in 5 lines from the current cursor position.

Case 5: Replace the whole word and not the partial word

:s/\<his\>/her/

The standard replace will make the word history with herstory. Enclose the word with < and > to ensure the search is for the whole word and not for partial one.

Case 6: Interactive Find and Replace

:%s/oldText/newText/gc

This will prompt for confirmation.

replace with newText (y/n/a/q/l/^E/^Y)?

y -> replace the highlighted word. After replace moves to the next word.
n -> does not replace the highlighted word. Moves to the next word.
a -> replace all the highlighted words.
l -> replaces the current highlighted word and terminates the find and replace.


Thanks

No comments:

Post a Comment

Followers

Powered By Blogger
 

RAC Database Administration. Copyright 2008 All Rights Reserved Revolution Two Church theme by Brian Gardner Converted into Blogger Template by Bloganol dot com