简体   繁体   中英

How to Grep Different words in Different lines in Linux

I am trying to monitor a log using tail -f command and when ever I come across two different words in different lines on same log, need to capture those and send a email notification:

For example: cat example.txt :

<event> 12345 </event>
<Description> Exception on file transfer for user ABC </Description>

I need to monitor for event '12345' having 'Exception' for user 'ABC'.

When I do tail -F example.txt | egrep "12345|Exception|ABC" tail -F example.txt | egrep "12345|Exception|ABC" This command prints if it sees any one of Grep keyword. Instead it needs to print only if it comes across all keywords in grep.

try

tail -f example.txt | egrep --line-buffered  "Exception.*ABC" -B 1 | egrep -v Description
  • "Exception.*ABC" search for lines having Exception AND ABC
  • "-B 1" is to have previous line (the event)
  • "--line-buffered" is to turn grep buffering mode (else the second egrep won't process)
  • "| egrep -v Description" finally removes the Description line (since you just want the event)

you will end up having

    <event> 12345 </event>

Play with each parameter to see the difference

regards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM