Vim Tip #10: Working With ex Scripts


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:

" stop appending text
" write the changes and quit:

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:

for file in $*
ex - $file << end-of-script

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.