1

I am learning to use grep and I tried to use the following commands to find entries in /var/log/messages file, but I get errors:

grep "Oct 23 21:22:44" | "80" /var/log/messages

I get error for this. Than I tried the following and replaced double quotes with single quotes:

grep 'Oct 23 21:22:44' | '80' /var/log/messages

This did not work either. Why is it wrong because we can search multiple patterns using pipe! Is it because Oct 23 21:22:44 and 80 are in different places!

80 and the date are in different orders in the file!

user5499177
  • 47
  • 2
  • 6

3 Answers3

4

this syntax:

grep "Oct 23 21:22:44" | "80" /var/log/messages

is equivalent to running grep and pass output to a file called 80.

A way to do What you need is enabling -E option (--extended-regexp) to be able to use | as-is, like this:

grep -E "Oct 23 21:22:44|80" /var/log/messages
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • Thank you reply! This does not give any error, but it only shows a new line. The date and number 80 are in different places in the file! Do you think that is causing problem? – user5499177 Nov 05 '16 at 20:52
  • It works now. I don't know why it did not work before! Thanks a lot for help! – user5499177 Nov 05 '16 at 21:01
  • 2
    The `-E` just allows you to use an unescaped pipe in the regular expression, but the character itself must *still* be escaped at the shell level. Any of `grep foo \\\| bar file`, `grep "foo \| bar" file`, `grep -E foo \| bar file`, or `grep -E "foo | bar" file` should work. – chepner Nov 05 '16 at 22:22
  • @chepner thanks for the precision. `-E` is still enabling "extended" regexes, so accepting `|` as-is is just a nice side effect I guess. – Jean-François Fabre Nov 06 '16 at 08:01
2

You can also use the -e option:

grep -e 'Oct 23 21:22:44' -e '80' /var/log/messages

If search terms doesn't require regular expressions, -F option can be used - it is faster as well as avoids need of escaping meta characters. Thanks @mklement0 for pointing it out.


Also, use single quotes unless you need to perform command substitution, parameter expansion, etc. Related: Why does my shell script choke on whitespace or other special characters?

Sundeep
  • 23,246
  • 2
  • 28
  • 103
1

There are 2 changes required to be done in your command:

  • For multiple search criteria in single GREP command use -E parameter

  • Combine all criteria with pipe chars. and no spaces in between.

grep -E "Oct 23 21:22:44|80" /var/log/messages

mklement0
  • 382,024
  • 64
  • 607
  • 775
user3676305
  • 65
  • 1
  • 8
  • 2
    `-E` is only needed to use an unescaped pipe in the regular expression. `grep "Oct 23 21:22:44\|80" ...` would work fine. – chepner Nov 05 '16 at 22:24