HomeUNIXOpen vim editor to first occurrence of search term

Open vim editor to first occurrence of search term

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?

Quinn McHenry
Quinn McHenry
Quinn was one of the original co-founders of Tech-Recipes. He is currently crafting iOS applications as a senior developer at Small Planet Digital in Brooklyn, New York.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

LATEST REVIEWS

Recent Comments

error: Content is protected !!