5

I am interested in mastering the art of using ex from the command line (vi -esc <commands> / ex -sc <commands>). I got the basics worked out, but one thing eludes me:

How do I add text using insert mode?

Let's say I want to add text at the end of the file. In interactive ex, I would do:

$ ex file.txt
:normal! G
$a
foo
.
x

But if I enter that same sequence as -c command line option when invoking ex, I get stuck on the interactive ex command line, and if I enter x from there, my file remains unchanged.

DevSolar
  • 789
  • 1
  • 7
  • 15

1 Answers1

5

The documentation for -s in Ex mode :help -s-ex states:

To be used when Vim is used to execute Ex commands from a file instead of a terminal.

So it seems the correct approach is to save your commands into a file and then run:

vim -es < commands.ex file.txt

N.B. Note that you don't need to use the Ex mode -e argument to run Vim commands non-interactively: the commands you add with -c are already interpreted as Ex commands, and you can have up to 10 of them (see :help -c), so you could also do something like:

vim -c "normal! G" -c "normal! ofoo" -c x file.txt

Or more concisely:

vim "+norm! Gofoo" +x file.txt
Rich
  • 31,891
  • 3
  • 72
  • 139
  • I don't really like the idea of going through external temporary files. Otherwise, thanks for the hint to split up the command string into multiple -c options. – DevSolar Jun 29 '17 at 10:59
  • 1
    @DevSolar In that case, see also garyjohn's answer here for one method of using a shell feature to avoid having to create a temporary file (and possibly the other answers on that page. – Rich Jun 29 '17 at 14:54