Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a series of vim commands from command prompt

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?

like image 679
imbichie Avatar asked Apr 23 '14 05:04

imbichie


People also ask

How do I run multiple commands in vim?

You can execute more than one command by placing a | between two commands. This example substitutes for htm, then moves on to JPEG, then GIF. The second command (and subsequent commands) are only executed if the prior command succeeds.

Can I use vim in CMD?

After its installation, you can use it by opening the command prompt (cmd) then typing “vim”. This will open the vim application. There are two modes available in this editor, one is the insert mode where you can insert anything you like then there is a command mode which is used to perform different functions.

How do I cycle between files in vim?

Using windows. Ctrl-W w to switch between open windows, and Ctrl-W h (or j or k or l ) to navigate through open windows. Ctrl-W c to close the current window, and Ctrl-W o to close all windows except the current one. Starting vim with a -o or -O flag opens each file in its own split.

How do I run a vim program in terminal?

Launching Vim In order to launch Vim, open a terminal, and type the command vim . You can also open a file by specifying a name: vim foo. txt .


1 Answers

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

like image 180
JimR Avatar answered Sep 20 '22 09:09

JimR