Open vim editor to first occurrence of search term

Contributor Icon Contributed by qmchenry Date Icon October 2, 2008  
Tag Icon Tagged: UNIX

I don’t want to admit how long I’ve been using vi as my go-to editor (although if vi had been born then, it would now be old enough to drink and vote). One of the things I love about vi is that you only need to know a few things to use it, but it has so many little tricks that you never seem to run out of new things to try. The ones that make your life easier will stick. I had never seen this one before — it’s a simple command line option for vim that includes a search term. When used, your cursor will be positioned at the first occurrence of the term.


To open a file to the first instance of a search term, use the following command line with vim:

vi +/searchterm filename

The + command line option tells the editor to run the text that follows as a command, just as if you typed it after vi had opened. In this case, we’re telling vi to search for ’searchterm’ with the standard forward slash command. Since it is the same as working with searches inside the editor, this command line shortcut is easy to remember. And just like normal vi searches, you can hit ‘n’ to advance to the next instance of the search term.

Just as you’d expect, if you are searching for text with a space in it, the normal command line rules apply. You can search for the text “one two” from the file file.txt in at least two ways, the escape-the-space-with-a-backslash or “enclose it in quotes” techniques:

vi +/one\ two file.txt
vi +/"one two" file.txt

I’ve tested this on various versions of vim I have installed, but I couldn’t find a system that has plain old vi installed. If you have access to our long lost vi, can you try this shortcut and let us know in the comments if it works?

Previous recipe | Next recipe |
 
  • oz
    works beautifully!! :) Thank you!!!!
    (vi on SCO unix )
  • nhmeanie
    Works fine on vi packaged w/Solaris 10
  • Ryan Jordan
    I have
    Version 1.79 (10/23/96) The CSRG, University of California, Berkeley.
    running on a
    SunOS cidermill 5.9 Generic_118558-26 sun4u sparc SUNW,Sun-Blade-100
    and it works the same.

    I was able to search and search/replace.

    Can't figure how to execute more than one command from the shell.
    Anyone know how to execute multiple commands at a time in VI?
  • flexinfo
    it just makes we wonder where these undocumented commands come from!! but its a nice one thanks makes sence really vi +/<search>. Then I would expect

    vi +:g/<old>/s//<new>/g <filename>

    To work and it does !!! thanks for the post and the previous comment that has opened a whole new range of possibilites:

    ~ Merry Christmas and Seasonal Greetings ~~
blog comments powered by Disqus