8

Say I want to grab the last 5 mentions of cron in /var/log/syslog.log looking over the grep manual it seems like I can't get grep to search in reverse. I can however grab the most recent occurrences.

grep cron -m 5 /var/log/syslog

Is there a reverse grep command I can use? :)

14

Following the usual unix philosophy of combining tools: use grep to search, and tail to return the last part of the file.

grep cron /var/log/syslog | tail -n 5
  • It would be faster to reverse the order if you know that the content you are interested in is within the last X lines. tail -n 100 < /var/log/syslog |grep cron – bk0 Dec 29 '14 at 21:34
  • Note this does not actually reverse the order, it just limits the grep to the bottom X lines. May or may not serve the purpose. – swornabsent Aug 12 '15 at 15:41
16

What about piping to tac?

http://linux.about.com/library/cmd/blcmdl1_tac.htm

tac  /var/log/syslog | grep cron -m 5
  • You need a second tac in the end, to reconstruct the original order, no tac /var/log/syslog | grep cron -m 5 | tac? Tacatac ... :) – user unknown May 7 '11 at 20:02
  • But isn't reverse order part of the request? Taaaac ^^ – neurino May 7 '11 at 22:22
  • Ah, maybe! I understood the reverse-part only as searching for the last ones. – user unknown May 8 '11 at 0:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.