David Lesner
David Lesner

Reputation: 11

Find exact word in file using egrep in bash

I have a file called F1. F1 contains

Hello abc@
aaa ddd

Now, I want to check the word abc is in file F1.

After running the following command

find $dir -type f -exec egrep -w "abc" {} \;

This is the output I get

Hello abc@

For some reason the word abc@ was also found. (I was looking for abc.)

Upvotes: 0

Views: 2775

Answers (3)

Tharanga Abeyseela
Tharanga Abeyseela

Reputation: 3483

find $dir -type f -exec grep -v [[:punct:]]  {} \; | grep -ow abc

Upvotes: 0

Barmar
Barmar

Reputation: 780724

This should do it:

egrep '(^| )abc( |$)' F1

It looks for abc surrounded by either space or line beginning/ending.

Upvotes: 4

Mark Plotnick
Mark Plotnick

Reputation: 10251

You're likely using GNU egrep - the -w option isn't part of the POSIX standard - and its manual page states

-w, --word-regexp
      Select  only  those  lines  containing  matches  that form whole
      words.  The test is that the matching substring must  either  be
      at  the  beginning  of  the  line,  or  preceded  by  a non-word
      constituent character.  Similarly, it must be either at the  end
      of  the  line  or  followed by a non-word constituent character.
      Word-constituent  characters  are  letters,  digits,   and   the
      underscore.

So @ is considered a non-word constituent character, just like , and . and whitespace.

If you have an idea of what you'd like the word separators to be, let us know and we can craft a regexp for you.

Upvotes: 2

Related Questions