execute VI command from bash script
Goal:
Execute a vi find-and-replace command and continue running bash script. This is as close as I've gotten: Code:
vi -e -c %s/DOMAINNAME/example.com/g template.conf Thanks! -Adam |
Quote:
Code:
sed -i 's/DOMAINNAME/example.com/g' <filename> |
Beautiful!
Thanks, -Adam |
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 Code:
printf '%s\n' '%s/Foo/Bar/g' 'w' | ed -s file.txt 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.) |
All times are GMT -5. The time now is 12:12 PM. |