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'.

3 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
  3. All the shortlisted on-line casinos right here offer a fantastic number of slot machines for players to enjoy, together with classic and video variations with loads of completely different themes to choose from|to choose from}. You can anticipate a thrilling expertise with any slots game on-line, with a spread of top 3 reel and 5 reel titles. We look out for casinos that provide loads of free slots, so find a way to|you probably can} spin just for fun, and great actual cash video games should you favor the joys of playing. The enchantment of slots has at all times been the atmosphere of suspense it creates with its spinning reels coupled with the enchantment of “easy” cash. The average particular person can simply set the minimum bet and 온라인카지노 playing in} easy as|is so simple as} urgent a button.

    ReplyDelete