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 "w
rite" command to the end of the sequence to save it back to file, just as you would in interactive vi
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).
printf '%s\n' '%s/Foo/Bar/g' 'w' | ed -s file.txt
How to use ed:
(also read the info page)
However, as mentioned by TB0ne, the best option for most simple edits is generally 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:
, 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.
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.)