How does `grep -w` work?

QuestionsQuestions4 SkillsProUser Account ManagementNov, 25 2025
0134

The grep -w command is used to search for whole words in a text. Here's how it works:

  • grep: This is the command-line utility for searching text using patterns.
  • -w: This option tells grep to match only whole words. A whole word is defined as a sequence of characters that is surrounded by word boundaries, such as spaces, punctuation, or the start/end of a line.

Example

If you run:

echo "joker jokers" | grep -w 'joker'

The output will be:

joker

In this case, 'joker' is matched, but 'jokers' is not, because it is not a whole word.

Summary

Using -w ensures that your search term is matched exactly as a standalone word, preventing partial matches. This is useful for precise searches in text files or command outputs.

If you want to practice more with grep, consider checking out relevant labs on LabEx!

0 Comments

no data
Be the first to share your comment!