Saturday, July 02, 2005

Tips: search and replace pattern in vi, sed...

sed awkI use vi a lot for my software development, both unix and java program. I am not an vi expert, just enough for my normal use, but search and replace in vi is troublesome for me, I get a 2 different answer from experience vi user, it work well for me, but when I ask them why there is 2 different format, they don't give me a well explain, so I just copy down and follow...

1. :g/<source>/s//<target>/g
2. :1,$s/<source>/<target>/g

I try to use other format, it just don't work.

Finally I read the O'Reilly's 'sed and awk' book, and figure out what is the format:
(this pattern works in sed, and ed too)

:[address]/<filter pattern>/s/[<pattern>]/<target>/[c,g]

address is optional ( shown by [ ] )
g, global, all the lines
n,m, line n to line m, $ stand for last line. eg. 1,$ is same as global

/filter pattern
filter out the pattern line by line, pattern is optional, if pattern is provided only those lines with filter pattern, will be search and replace

the 2nd [pattern] after s/ is the search pattern
if the search pattern is not provided, the pattern will follow the (1st) filter pattern, but the search pattern could be different from the filter pattern. eg. :g/hello world/hello/Hello/

replace pattern
the target pattern that you want.

the final [c,g]
c, confirm 1 by 1
g, global, all, (for the line only), if replace all line must specified in address. if nothing is provided, only the 1st exist pattern will be replace. eg. the there is 2 'hello world' exist in each line, only the 1st 'hello world' will change to 'Hello world', with capital 'H'.

No comments: