Lessons · Terminal · grep -w: whole words only
Whole words only
A pattern matches anywhere in a line, so grep cat finds concatenate. -w requires a word boundary on both sides.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
It is the difference between an answer and a page of near-misses.
How to think about it
Reach for -w whenever the thing you are looking for is a word rather than a fragment.
Worked example
grep cat words.txtAll three. The middle one is not about cats.
grep -w cat words.txtTwo. Whole words only.
grep -c -w cat words.txt2, counted rather than listed.
Your turn
Match log as a whole word only.
grep log app.log
Try it at a real prompt
The trap
If -w is still too loose, stop sharpening the pattern and narrow the input: cut the column out first and search that.
Practise grep -w: whole words only on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.