Monday, June 30, 2008

Command-Line Vim

Before anybody says anything, I know this can often be better accomplished using sed, perl, <your favorite tool>. That said, you can use any command in the ex toolbox directly from the command-line without actually opening Vim. Any argument preceeding the filename to be edited that begins with a plus symbol (+) is taken as an ex-command. Alternatively, you can use the -c command line flag to indicate an ex-command is being specified. This has two handy uses. For one, you can pre-process a file with an ex-command before it's loaded into Vim. Secondly, you can use Vim in a script non-interactively. For example:

travis@travis-ubuntu:/home/travis% echo "hello world" > fun.txt
travis@travis-ubuntu:/home/travis% vim "+s/hello/goodbye cruel/" "+wq" fun.txt
travis@travis-ubuntu:/home/travis% cat fun.txt
goodbye cruel world

You could get an identical result with:

vim -c "s/hello/goodbye cruel/" -c "wq" fun.txt

As an aside, this is the 100th post to Daily Vim. I want to thank everyone who's contributed to the blog so far and made this a great learning experience. You guys have made this a really fun project, so keep the comments coming!


Anonymous said...

When using vim as a sed replacement, you may consider using the -e -s flags to disable the UI completely.

One of my favorite uses of this is to convert code to html using vim:

vim -e -s +:TOhtml +w +qa file.c

Anonymous said...

Ooops... seems there is a bug with the -s option. So my example doesn't work, but this does:

vim -e +:TOhtml +w +qa file.c

Dr Foobario said...


bartman thats crazy, but awesome!