How to do whole-word search similar to "grep -w" in Vim
VimGrepVim 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.