linux - How to grep for lines which contain particular words in a log file?

ID : 274516

viewed : 52

Tags : linuxbashshellgreplinux





Top 4 Answer for linux - How to grep for lines which contain particular words in a log file?

vote vote

97

I would use a regular expression, like this:

grep -E 'hello|world|tester' abc.log 
vote vote

87

If you store your patterns in a file, one per line, you can use grep -f file-with-patterns file-to-search.log

From the man page:

   -f FILE, --file=FILE           Obtain  patterns  from  FILE,  one  per  line.   The  empty file           contains zero patterns, and therefore matches nothing.   (-f  is           specified by POSIX.) 

Edit 2018:

Since I wrote this, I have become aware of the following interesting edge cases:

  • You can read the list of patterns from pipe using -f - (if you don't need stdin, i.e. you specified files on grep's command line) or -f <() (in any case)
  • grep's performance starts to fail badly if hundreds of patterns are passed. If your use case is that insane, consider generating and immediately executing a sed (or some other language) script, although this could potentially have problems with overlapping patterns.
vote vote

73

Apart from bruchowski's answer, you can also use:

grep -i -e "hello" -e "world" -e "tester" abc.log 

OR

grep 'hello\|world\|tester' abc.log 

OR

egrep 'hello|world|tester' abc.log 
vote vote

60

Top 3 video Explaining linux - How to grep for lines which contain particular words in a log file?







Related QUESTION?