Vi Tip of the Week: Searching

This is part of a series of tips on using Vi.  To see the complete series, click here.

If you want to search for something in a file, you can use the forward slash character: /. Type forward-slash, the text that you want to search for, then press the Return key.  Vi will take you to the next place in the document where that text appears, and will place the cursor on the first character.  So, if I wanted to search for my name, Shane, I would type:

/Shane

and press Return.  If the text doesn’t appear in the file, I’ll get a message on the status line telling me that (the exact contents of the message depend on which version of vi you are running).

If you want to search for the same text again, you can just type the forward slash followed by Return — vi will remember what the last text you searched for, and will search for it again.  But, if you type anything after the slash, it will search for that instead.

Another thing you can do to search for the same text is to press the n key — it will take you to the next occurrence of that text!

/ searches forward; if you want to search backwards, use the question mark instead.  If I want to search for the previous occurrence of my name, I type

?Shane

And if I want to search for the same text again, it works just like the forward slash — type ? followed by Return, and it remembers what I searched for last, and searches backwards for that again.

OK, here’s some magic — if I press n, it searches in the same direction as my last search! If I had been searching forward, then press n to search for the same text, it searches forward.  But, if I had been searching backward with ?, pressing n will now search backward for the same text!

The search string can also include some simple regular expressions.  If I want to search for my name at the start of a line of text, I use ^:

/^Shane

Or, if I want to search for it at the end of a line of text, I use $:

/Shane$

Finally, if I want to go back to the line I was on just before my previous search, I can press the backquote twice: “.  This will take me to my previous position.

Have fun with searching!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.