16

I want to search for multiple strings in a log file. Only those entries should be highligted where all the search strings are there in same line. Can i use less command for this or any other better option. My log file size is typically few GBs.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
Satish
  • 1,037
  • 1
  • 13
  • 20

2 Answers2

22

When you want to search for string1 or string2, use /string1|string2. You said you wanted lines where you find both:

/string1.*string2

When you do not know the order in the line and want to see the complete line, you will need

/.*string1.*string2.*|.*string2.*string1.*

Or shorter

/.*(string1.*string2|string2.*string1).*

Combining more words without a fixed order will become a mess, and filtering first with awk is nice.

Walter A
  • 19,067
  • 2
  • 23
  • 43
  • Thanks! It worked for me. I personally prefer less over awk because of "if file is open i can quickly change the search string, search forward/backward from the current location." Ability to search for multiple strings with less is a bonus. – Satish Jan 29 '17 at 06:58
  • You prefer it because this answer just tackles *two* search patterns. This get's super complicated when you increase the number of patterns or the patterns are more complex. *three* patterns are almost impossible to type. – hek2mgl Jan 29 '17 at 09:03
  • @hek2mgl agree, in my case order of search strings is known and i have just 2 or 3 search strings max, so its preferred. Otherwise like you suggested awk with less is the way to go. – Satish Jan 29 '17 at 15:29
4

Use awk to filter the file and less to view the filtered result:

awk '/pattern1/ && /pattern2/ && /pattern3/' file.log | less

If the file is big you may want to use stdbuf to see results earlier in less:

stdbuf awk '/pattern1/ && /pattern2/ && /pattern3/' file.log | less
hek2mgl
  • 152,036
  • 28
  • 249
  • 266