Vim Tip #10: Working With ex Scripts

2018-11-19(Mon)

tags: Vim

Vim Tips

Make sure you're familiar with Tip #5: Ex Mode before working through this one.

I admit this isn't a strength of mine, but I've played with it occasionally for years. And I find it fascinating and sometimes very useful. 'ex' is the underlying line editor that vi was originally based on. (Now ex is based on vi.) You can create a script:

" file: addhtmlend.ex
" This is a comment, just as in VimScript
" go to the end of the document and append some text:
$a
</body>
</html>

.
" stop appending text
" write the changes and quit:
w
q

Then run it against a file with:

ex unterminated.html < addhtmlend.ex

Another way to use this that doesn't require an external file is to embed the ex usage inside the Bash file with a 'here' document:

#!/bin/bash
for file in $*
do
ex - $file << end-of-script
g/thier/s//their/g
g/writeable/s//writable/g
wq
end-of-script
done

I borrowed this example from my very ancient copy of O'Reilly's Learning the vi Editor.

Vim and NeoVim can also be scripted this way - which might be more familiar. You may have noticed the $ to go to the end of the file for ex, whereas we're adjusted to G to go to the end of the file in vim and $ to go to the end of the line. Likewise, instead of <Esc>, ex uses a single . as the terminator for text input.