1

I am using this snippet code (just delete first line with ed). I wanna know if i can make something like this in vim. I wrote the script and passed the file as an argument.

file:

# This is a comment #

foo bar

edit with ed:

ed $1 << EOF
1/^[ ]*$/d
w 
q
EOF

I tried with vim:

vi $1 << EOF
dd
w 
q
EOF

> Vim: Warning: Input is not from a terminal
toblerone_country
  • 577
  • 14
  • 26
Roman Kiselenko
  • 43,210
  • 9
  • 91
  • 103

2 Answers2

6

You can start vim in 'ex' mode and feed it the commands:

vim -E -s yourfile <<EOF
:1d
:update
:quit
EOF

But it would be more appropriate just to use sed in this case:

sed '1d' yourfile
4

Alternatives

Unless you really need special Vim capabilities, you're probably better off using non-interactive tools like sed, awk, or Perl / Python / Ruby / your favorite scripting language here.

Your example, with sed:

$ sed -i -e '1d' $1

That said, you can use Vim non-interactively:

Silent Batch Mode

For very simple text processing (i.e. using Vim like an enhanced 'sed' or 'awk', maybe just benefitting from the enhanced regular expressions in a :substitute command), use Ex-mode.

REM Windows
call vim -N -u NONE -n -i NONE -es -S "commands.ex" "filespec"

Note: silent batch mode (:help -s-ex) messes up the Windows console, so you may have to do a cls to clean up after the Vim run.

# Unix
vim -T dumb --noplugin -n -i NONE -es -S "commands.ex" "filespec"

Attention: Vim will hang waiting for input if the "commands.ex" file doesn't exist; better check beforehand for its existence! Alternatively, Vim can read the commands from stdin. Your example would be something like this:

$ vim -e -s $1 << EOF
1delete
wq!
EOF

Full Automation

For more advanced processing involving multiple windows, and real automation of Vim (where you might interact with the user or leave Vim running to let the user take over), use:

vim -N -u NONE -n -c "set nomore" -S "commands.vim" "filespec"

Here's a summary of the used arguments:

-T dumb           Avoids errors in case the terminal detection goes wrong.
-N -u NONE        Do not load vimrc and plugins, alternatively:
--noplugin        Do not load plugins.
-n                No swapfile.
-i NONE           Ignore the |viminfo| file (to avoid disturbing the
                user's settings).
-es               Ex mode + silent batch mode -s-ex
                Attention: Must be given in that order!
-S ...            Source script.
-c 'set nomore'   Suppress the more-prompt when the screen is filled
                with messages or output to avoid blocking.
Ingo Karkat
  • 167,457
  • 16
  • 250
  • 324