How to run a series of vim commands from command prompt

imbichie picture imbichie · Apr 23, 2014 · Viewed 28.4k times · Source

I have four text files A.txt, B.txt, C.txt and D.txt I have to perform a series of vim editing in all these files. Currently how I am doing is open each files and do the same vim commands one by one.

Is it possible to make a script file which I can run from the command prompt, means without open the actual file for vim editing.

for example, if I have to perform the below vim commands after opening the A.txt file in vim editor:

:g/^\s*$/d
:%s/^/[/
:%s/\(.*\)\(\s\+\)\(.*\)/\3\2\1
:%s/$/]/
:%s/design/test/

Is it possible to make a script file and put all these commands including gvim A.txt (first command in the file). and edit run the script file from command prompt.

If it is possible, please let me know how to do it and how it can be done with single or multiple files at a time?

Answer

JimR picture JimR · Apr 23, 2014
vim -c <command> Execute <command> after loading the first file

Does what you describe, but you'll have to do it one file at a time.

So, in a windows shell...

for %a in (A,B,C,D) do vim -c ":g/^\s*$/d" -c "<another command>" %a.txt

POSIX shells are similar, but I don't have a machine in front of me at the moment.

I imagine you could load all the files at once and do it, but it would require repeating the commands on the vim command line for each file, similar to

vim -c "<command>" -c "<command>" -c ":n" (repeat the previous -c commands for each file.)  <filenames go here>

EDIT: June 08 2014: Just an FYI, I discovered this a few minutes ago.

vim has the command bufdo to do things to each buffer (file) loaded in the editor. Look at the docs for the bufdo command. In vim, :help bufdo