myfile.txt contains the following:
hello (ab)
hello ab
hello abcdI've tried the following command:
$grep '\<ab\>' myfile.txt\< means a beginning of a word and \> means end of word.
So I thought my grep command is equivalent to $grep ' ab ' myfile.txt.I expected my output to be
hello abBut it matches:
hello (ab)
hello abHow is a word defined? Is it a string with a space in front of it and one more space following the string?
12 Answers
From man grep
The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]].
In other words, a word is a sequence of alphanumeric characters and underscores, and a word boundary is the empty string before or after anything else - including punctuation such as ( and ) as well as whitespace. So:
$ echo 'word-boundary' | grep -o '\<\w*\>'
word
boundary
$ echo 'word_boundary' | grep -o '\<\w*\>'
word_boundary
$ echo 'word(bound)ary' | grep -o '\<\w*\>'
word
bound
aryFor more information see Regex Tutorial - Word Boundaries.
If you want to search for an exact word, you need to use the option -w. See the below command:
grep -w "hello ab" file.txtthe output is as you expected.
hello abIf you want the exact name "hello ab" then use -w option with grep command.
For learning more options of grep command, please refer the article for grep command written by me: