How to match exact word and string using grep

Here is my data file

foo 3535 ab 3355
bar 55523 gdg 6646
foo1 333 xzzz 555
foobar 555 zztt 56
FOO 333 44 66 7
foo 5555 tttt 7777

I type

grep foo input.txt

I get

foo 3535 ab 3355
foo1 333 xzzz 555
foobar 555 zztt 56
foo 5555 tttt 7777

however, i only want:

foo 3535 ab 3355
foo 5555 tttt 7777

Is it possible? How do I tell that to grep? How can I match exact word and string using grep?

How about?

grep "\<foo\>" your_file_name

The \<word\> matches exact words. If you want to match FOO line too, pass the -i option:

grep -i "\<foo\>" your_file_name
1 Like

Simple:

grep -w "word" filename
grep -i -w "word" filename
grep -i -w "string" filename
# matching multiple words or strings with egrep
grep -E -i -w "word1|word2|word3" input 
egrep -i -w "str1|str2" my.txt

grep options are as follows for matching exact words/strings:

  1. -w : match only whole words
  2. -i : Ignore case distinctions in patterns i.e. all cases matched. For instance, foo, FOO, Foo, FoO and so on.
  3. -E : Extended regular expressions

See our help pages:


and
1 Like

Linux sysadmin blog - Linux/Unix Howtos and Tutorials - Linux bash shell scripting wiki