0

The following commands work fine when I issue them from the command mode in Vim:

:%s/\(^\s\+\)\(\S\+.*)\s*\){$/\1\2\r\1{/g
:g/^\s*\/\/$/d

But when I run the above commands as a script as below:

vim -c "commands.vim" myfile.c

I get errors:

enter image description here

Note: I am aware of this question: How to use "-c" command line option? but it has not helped with the error.

1
  • 3
    -c expects a Vim command. Merely mentioning a vimscript is not a command. Nov 23, 2017 at 8:08

2 Answers 2

2

Vim's -s {scriptin} command line argument* allows you to supply a file the contents of which will be interpreted as if you had typed them in, character by character.

This can be used for normal mode commands, but because you also generally enter command-line mode commands by typing them in, it works fine for ex commands too, so long as you include the colons at the start of each line (as you have).

vim -s commands.vim myfile.c

See :help -s for more details.

* Not to be confused with Vim's other -s argument, which only applies when ex mode is also specified: see :help -s-ex

0

Based on comment from ChristianBraband, I found a solution, with help from this page: https://en.wikibooks.org/wiki/Learning_the_vi_Editor/Vim/Modes

Modify the commands.vim script so that file update and quit are included at the end:

:%s/\(^\s\+\)\(\S\+.*)\s*\){$/\1\2\r\1{/g
:g/^\s*\/\/$/d
:update
:quit

Run from the command line as follows:

vim -c "source commands.vim" myfile.c

Update: Removed the unnecessary -E option per comment from @Rich.

8
  • 1
    vim -s commands.vim myfile.c is a bit simpler. See :h -s (and note difference from :h -s-ex).
    – Rich
    Nov 23, 2017 at 16:33
  • @Rich Yes, this works and it is what I was after originally. If you can post it as an answer, I'll accept. Thank you.
    – Sabuncu
    Nov 23, 2017 at 17:36
  • @Rich By the way, what a poor command-line design, having -s-ex and -s!
    – Sabuncu
    Nov 23, 2017 at 20:09
  • I concur! Note that with your solution you don't need the colons at the start of each line (although it works fine with them).
    – Rich
    Nov 23, 2017 at 23:20
  • @Rich Yet colons are required for -s (scriptin)! Another inconsistency. When I tried -s (scriptin) without colons, the whole thing exploded and the script itself got inserted into the file.
    – Sabuncu
    Nov 24, 2017 at 8:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.