Valhalla Legends Forums Archive | General Discussion | Find/Replace in vi

AuthorMessageTime
iago
I've never been able to figure this out. In vi, how do you do global substitions across a file? :s/a/b/g does a substitution across the line, but not the file.
February 22, 2004, 1:07 AM
Thing
sed would probably be better to accomplish that task.
February 22, 2004, 1:17 AM
Kp
Specify the range of lines you want affected. If you don't, it assumes current line only. Some examples:

:%s/foo/bar/ -- substitute across the entire file
:.,$s/foo/bar/ -- substitute on this line and all lines through to the end of the file
:10,.s/foo/bar -- from line 10 to the current line (dot).
:'a,'bs/foo/bar/ -- from mark a to mark b

You can also do arithmetic expressions. I often find myself doing :.,.+10s/.../---/ to get this line and the ten following it. Arithmetic should work on any of the above expressions (though it doesn't make much sense to add to $, which is end of file anyway). You could do $-10 to get until 10 lines shy of end-of-file.
February 22, 2004, 5:00 PM
iago
Ah, it was the '%' that I needed. I used to know that, but I had forgotten.

Thanks! :)
February 22, 2004, 6:07 PM

Search