Skip to content
shellhacks.dev
Text Processing

Match whole words only

Match whole words only with grep -w. A match must sit between non-word characters, and letters, digits and the _ character all count as word characters.

1 min read
Summarize in AI

Searching for cat also finds concat and category, and you want only the lines that hold the word on its own.

Shell
printf 'cat\nconcat\ncat-food\ncat_food\nthe cat sat\n' | grep -w cat
Text
cat
cat-food
the cat sat

With -w grep accepts a match only if the character before it and the character after it are not word constituents, which are letters, digits and _, as the GNU grep manual describes. That is why cat-food matches and cat_food does not. Grep also tries again at a later position in the same line when the first match fails the test, so a line can still match.

The check is about the edges of the match, so it does not help with a pattern that itself contains a space or punctuation. For custom word boundaries use grep -P '(?<![A-Za-z])cat(?![A-Za-z])' with GNU grep built with PCRE. BSD grep accepts -w too.

Share

More snippets

Text Processing

Search recursively and skip binary files

Skip binary files in a recursive grep with --binary-files=without-match, short form below. Otherwise GNU grep 3.8 prints a notice for every binary hit.

1 min read
Text Processing

Count the matches per file

Count the matching lines in each file with grep -c. With several files grep prefixes each count with the name, and -h removes the prefix for one total.

1 min read
Text Processing

Count every occurrence not just lines

Count every occurrence of a word with grep -o piped to wc -l, because grep -c counts the lines that match and a line with three hits counts as one.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.