Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open Vim from within a Bash shell script

Tags:

linux

bash

vim

I want to write a Bash shell script that does the following:

  1. Opens a file using Vim;
  2. Writes something into the file;
  3. Saves the file and exits.
echo 'About to open a file'
vim file.txt  # I need to use vim application to open a file
# Now write something into file.txt
...
# Then close the file.
...
echo 'Done'

Is that possible? I found something called Vimscript, but not sure how to use it. Or something like a here document can be used for this?

Update: I need to verify that Vim is working fine over our file system. So I need to write script that invokes Vim, executes some command, and closes it. My requirements do not fit into doing stuffs like echo 'something' > file.txt. I got to open the file using Vim.

like image 872
webminal.org Avatar asked May 12 '11 12:05

webminal.org


3 Answers

ex is the commandline version for vi, and much easier to use in scripts.

ex $yourfile <<EOEX
  :%s/$string_to_replace/$string_to_replace_it_with/g
  :x
EOEX
like image 162
Konerak Avatar answered Nov 06 '22 22:11

Konerak


Vim has several options:

  • -c => pass ex commands. Example: vim myfile.txt -c 'wq' to force the last line of a file to be newline terminated (unless binary is set in some way by a script)
  • -s => play a scriptout that was recorded with -W. For example, if your file contains ZZ, then vim myfile.txt -s the_file_containing_ZZ will do the same as previously.

Also note that, invoked as ex, vim will start in ex mode ; you can try ex my_file.txt <<< wq

like image 24
Benoit Avatar answered Nov 06 '22 21:11

Benoit


You asked how to write "something" into a text file via vim and no answer has necessarily covered that yet.

To insert text:

ex $yourfile <<EOEX
  :i
  my text to insert
  .
  :x
EOEX

:i enters insert mode. All following lines are inserted text until . is seen appearing by itself on its own line.

Here is how to search and insert as well. You can do something such as:

ex $yourfile <<EOEX
  :/my search query\zs
  :a
  my text to insert
  .
  :x
EOEX

This will find the first selection that matches regex specified by :/, place the cursor at the location specified by \zs, and enter insert mode after the cursor.

You can move \zs to achieve different results. For example:

ex $yourfile <<EOEX
  :/start of match \zs end of match
  :a
  my text to insert 
  .
  :x
EOEX

This will change the first occurrence of "start of match end of match" to "start of match my text to insert end of match".

If you want to allow any amount of whitespace in your searches between keywords, use \_s*. For example, searching for a function that returns 0: :/\_s*return\_s*0}

like image 8
Patrick Michaelsen Avatar answered Nov 06 '22 23:11

Patrick Michaelsen