Execute a command within Vim from the command line

vim

Is there a way to execute a Vim command on a file from the command line?

I know the opposite is true like this:

:!python %

But what if I wanted to :retab a file without opening it in Vim? For example:

> vim myfile.c
:retab | wq

This will open myfile.c, replace the tabs with spaces, and then save and close. I'd like to chain this sequence together to a single command somehow.

It would be something like this:

> vim myfile.c retab | wq

Best Solution

This works:

gvim -c "set et|retab|wq" foo.txt

set et (= set expandtab) ensures the tab characters get replaced with the correct number of spaces (otherwise, retab won't work).

I don't normally use it, but vim -c ... also works

The solution as given above presumes the default tab stop of eight is appropriate. If, say, a tab stop of four is intended, use the command sequence "set ts=4|set et|retab|wq".