How to do whole-word search similar to "grep -w" in Vim

VimGrep

Vim Problem Overview


How do I do a whole-word search like grep -w in Vim, which returns only lines where the sought-for string is a whole word and not part of a larger word?

grep -w : Select only those lines containing matches that form whole words.

Can this be done in Vim?

Vim Solutions


Solution 1 - Vim

\<bar\>

matches bar but neither foobar nor barbaz nor foobarbaz.

Use it like this in a substitution:

:s/\<bar\>/baz

Use it like this to list all the lines containing the whole word bar:

:g/\<bar\>

:h pattern is a good read.

Solution 2 - Vim

You want /\<yourword\>.

If your cursor is on a word, then you can press * and it will do a word-only search for the word under the cursor.

Solution 3 - Vim

One can use 'very-magic' \v to simplify the command:

/\v<yourword>

As mentioned in comments, \v indicates that all non-alphanumeric characters have special meaning hence one needs to enter only < and > rather than escaping them with \< and \>.

Solution 4 - Vim

map w /\v<><Left>

This mapping is using magic with the addition of moving cursor position between the "<" and ">" pair. As soon as press 'w', you can type your word right away, and enter to perform a wholeword search.

Of course instead of 'w' you can pick your favorite letter for mapping.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1420463View Question on Stackoverflow
Solution 1 - VimromainlView Answer on Stackoverflow
Solution 2 - VimAndy LesterView Answer on Stackoverflow
Solution 3 - VimrnsoView Answer on Stackoverflow
Solution 4 - Vimuser1500049View Answer on Stackoverflow