There's nothing wrong with using
vi/vim for this. In fact, the gnu version of the
ex editing command is actually equivalent to "
vim -es", which I think is probably easier to use than
vim -ec. You can simply feed it any sequence of ex-mode commands from stdin that you want, without having to worry about special formatting or escaping or whatever.
In any case, you just need to add a "
write" command to the end of the sequence to save it back to file, just as you would in interactive
vi.
Code:
printf '%s\n' '%s/Foo/Bar/g' 'w' | ex file.txt
A similar, but lighter, command is
ed. The basic syntax for most actions is pretty much identical to
ex (although it doesn't have anywhere near the range and flexibility).
Code:
printf '%s\n' '%s/Foo/Bar/g' 'w' | ed -s file.txt
How to use ed:
http://wiki.bash-hackers.org/howto/edit-ed
http://snap.nlc.dcccd.edu/learn/nlc/ed.html
(also read the info page)
However, as mentioned by TB0ne, the best option for most simple edits is generally
sed.
sed works pipeline-style and simply runs through the file once, one line at a time, from top to bottom. So as long as the edits don't cross line boundaries, it's usually easier and more efficient.
Here are a few useful sed references:
http://www.grymoire.com/Unix/Sed.html
http://sed.sourceforge.net/grabbag/
http://sed.sourceforge.net/sedfaq.html
http://sed.sourceforge.net/sed1line.txt
http://www.catonmat.net/series/sed-one-liners-explained
vim and
ed, OTOH, load the whole file into a memory buffer before editing, which makes them a bit slower, but does also allow you to operate on the whole file in random-access fashion. This makes multi-line work in particular much easier than with
sed. Plus, you can easily save the buffer directly back to file, either the original or a new one.
(
gnu sed also offers the
-i option for saving back to the original file, but note that this is actually just using a tempfile behind the scenes to do so.)