the way grep command \< and \> work

myfile.txt contains the following:

hello (ab)
hello ab
hello abcd

I'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 ab

But it matches:

hello (ab)
hello ab

How is a word defined? Is it a string with a space in front of it and one more space following the string?

1

2 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
ary

For 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.txt

the output is as you expected.

hello ab

If 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:

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like