Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing Vim commands in a shell script

I am writing a Bash script that runs a command-line program (Gromacs), saves the results, modifies the input files, and then loops through the process again.

I am trying to use Vim to modify the input text files, but I have not been able to find a way to execute internal Vim commands like :1234, w, x, dd, etc. from the .sh file after opening my input files in Vim ("vim conf.gro").

Is there a practical way to execute Vim commands from the shell script?

like image 401
Nikolkj Avatar asked Sep 17 '13 21:09

Nikolkj


People also ask

How do I run a Vim command in terminal?

You can run the shell commands from inside of Vim by just using :! before the command, : means you have to be in command mode. Just after being in command mode, the ! or bang operator will execute the command typed after it from the terminal(Linux/ macOS) or your default shell(Windows -> CMD/Powershell).

Can you run commands from Vim?

You can run commands in Vim by entering the command mode with : . Then you can execute external shell commands by pre-pending an exclamation mark ( ! ). For example, type :! ls , and Vim will run the shell's ls command from within Vim.


2 Answers

I think vim -w/W and vim -s is what you are looking for.

The "Vim operations/key sequence" you could also record with vim -w test.keys input.file. You could write the test.keys too. For example, save this in the file:

ggwxjddZZ

This will do:

Move to the first line,
move to the next word,
delete one character,
move to the next line,
delete the line, and
save and quit.

With this test.keys file, you could do:

vim -s test.keys myInput.file

Your "myInput.file" would be processed by the above operations, and saved. You could have that line in your shell script.

VimGolf is using the same way to save the user's solution.

like image 83
Kent Avatar answered Sep 23 '22 20:09

Kent


You can script Vim via the -c flag.

vim  -c "set ff=dos" -c wq mine.mak

However that only gets you so far.

  • From the commands you gave it looks like you are trying to run some normal commands. You will need to use :normal. e.g. :norm dd
  • Writing all this on the command line is asking for trouble. I suggest you make a Vim file (e.g. commands.vim) and then :source via -S.
  • You probably want to get good and conformable Vim's ex commands. Take a look at :h ex-cmd-index

So you will end up with something like this. With all your Vim commands inside of commands.vim.

vim -S commands.vim mine.mak

You may also want to look into using sed and/or awk for text processing.

like image 30
Peter Rincker Avatar answered Sep 24 '22 20:09

Peter Rincker