Valhalla Legends Archive

General => General Discussion => Topic started by: iago on February 21, 2004, 07:07 PM

Title: Find/Replace in vi
Post by: iago on February 21, 2004, 07:07 PM
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.
Title: Re:Find/Replace in vi
Post by: Thing on February 21, 2004, 07:17 PM
sed would probably be better to accomplish that task.
Title: Re:Find/Replace in vi
Post by: Kp on February 22, 2004, 11:00 AM
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.
Title: Re:Find/Replace in vi
Post by: iago on February 22, 2004, 12:07 PM
Ah, it was the '%' that I needed.  I used to know that, but I had forgotten.

Thanks! :)