Vivek Gaur
Vivek Gaur

Reputation: 4787

grep is not working as expected

i have tried to grep in a file ...... in file i have 5 entities

vivek
vivek.a
a.vivek
vivek_a
a_vivek

when i grep as grep -iw vivek filename, then it should give me vivek only but it give

vivek
vivek.a
a.vivek

Upvotes: 2

Views: 4174

Answers (3)

sahaj
sahaj

Reputation: 842

A set of characters with letters, underscore and digits is considered as a word. So any other character apart from that set denotes the word boundary. Therefore, in the line "vivek.a", the dot denotes end of word, and all the characters before that form a word "vivek", which matches with the word you are trying to match using option -w.

So, one way is to define your own word boundaries like this:

$ grep -i -e "[[:space:]]vivek[[:space:]]" -e "^vivek[[:space:]]" -e "[[:space:]]vivek$" -e "^vivek$" file

Upvotes: 1

wallyk
wallyk

Reputation: 57774

It does that because the definition of a word (which is what the w option chooses) permits . to separate words, though _ is considered part of a word. This definition is useful for programming languages, but not so useful for English text.

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798576

Looks fine to me. . is a non-word character. If you meant something else then you should have used a more-specific regex instead of using -w.

Upvotes: 2

Related Questions