Grep multiple exact word

Hi
I am trying to grep multiple exact word from log file and directing it to a new file.
however my log file has many numeric values, such as 0400, 0401, 0404
and all html error also starts with 404, 401 etc
so I just want to grep only when 404, 401 etc is coming, NOT 0400, OR 0401
i have written below code, but when i run it takes all 0400 etc and 400, , i just need the line when only exactly 404 is coming
please help

find /home/bharat/ -type f -name "apache_logs.txt" |while read file
  do
    RESULT=$(egrep "400|401|403|404|405" $file)
      if [[ ! -z $RESULT ]]
         then
            echo "Error(s) in $file on $HOSTNAME at "$(date)": $RESULT">> email_result.txt 
     fi
  done

man grep yields:

       -F, --fixed-strings
              Interpret PATTERN as a list of fixed strings (instead of regular
              expressions), separated by newlines,  any  of  which  is  to  be
              matched.

Please use code tags.
Try

if egrep "[^0](400|401|403|404|405)" file; then echo errors; fi
1 Like
egrep "\<(400|401|403|404|405)\>" $file

Why not use an expression like [^0]40[01345]" with appropriate wrapping to make them whole 'words' if needed. Can you share some of the data you want to work through and highlight in green the ones you want to match, with red for those you want to avoid?

Thanks, in advance,
Robin

Try:

grep -w '40[01345]' file
1 Like

Also

grep -w -e 400 -e 401 -e 403 -e 404 -e 405 file

or

grep -w '400
401
403
404
405' file

might work.

Unfortunately, the grep -w option is not included in the standards, so it might or might not work on your system. (This is one of the reasons why you should always tell us what operating system you're using when you start a thread here.)

If grep on your system supports the -w option, it is a great choice for what you are trying to do. Otherwise, please tell us what operating system you are using and show us some representative sample data so we can make alternative suggestions to help you.

Hi.

There is a grep work-alike written in perl at https://fastapi.metacpan.org/source/BDFOY/PerlPowerTools-1.013/bin/grep which implements the -w option:

    -w  Matches must start and end at word boundaries. This is currently
        implemented by surrounding each pattern with a pair of "\b", the Perl
        regular expression word boundary metasequence. See perlre for the
        precise definition of "\b".

This is one of a number of the (BSD) *nix tools written in perl. So if you have perl , you could get this capability. I have used this in situations where the local toolset does not include a useful option. A list and links to that toolset is at PerlPowerTools-1.013 - BSD utilities written in pure Perl - metacpan.org

Best wishes ... cheers, drl

1 Like