December 13, 2010

How to execute vim commands from the command line

I was trying to execute a regular expression over multiple lines when I ran across an example of how to execute vim commands from the command line. I happen to know how to do this from inside vim, so this was a serendipitous find. First, I'm going to show an example of how to do a simple replace. Here's the current contents of our test file

mike@shiner $ cat test_regex.txt
this is
a test

We can run the following command to replace 'this' with 'there'.

mike@shiner $ vim test_regex.txt -c '%s/this/there/' -c 'wq'
mike@shiner $ cat test_regex.txt
there is
a test

The -c arguments are executed sequentially. They're equivalent to typing : and then the contents of the argument. In the example above, we do a search/replace and then write/quit the file. If the "-c 'wq'" is omitted, then vim will remain open. Now back to what I was trying to do originally.

mike@shiner $ vim test_regex.txt -c '%s/there\_.*a/regex' -c 'wq'
mike@shiner $ cat test_regex.txt
regex test

The \_ tells vim that the . will include the new line character. Hence, the expression states that we want to match 'there' and 'a' and anything between these characters. This match is replaced with 'regex'.

2 comments:

  1. You can also do multiple, pipe-separated commands in one -c:
    vim test_regex.txt -c '%s/this/there/|wq'
    Which basically is just taking advantage of being able to do the same thing in vim.

    ReplyDelete
  2. Wow....that is soo cool!!! I didn't know you could do that. Thanks for the info.

    ReplyDelete