Grepping for the last item in a file

I am regularily grepping a file looking for a line that appears after an application is restarted. In this particular case Tomcat and its catalina.out file.

This was working fine, until the Java, Tomcat and Application got upgraded. The issue is, previously the restart of Tomcat would start a new catalina.out file meaning there would only be one entry to find. Now the catalina.out file is being appended to, so there can now be multiple entries of the text I am looking for. I am only interested in the last one.

Here is the OLD command I was using:

grep -A10 -B10 "INFO: Server" /var/log/tomcat/catalina.out

I would keep running this command until the application had started, and know it had not crashed on startup. It usually took a minite or two to start.

Now that the line I am looking for can appear multiple times in the file, due to previous starts etc. I now have to use the following:

tac /var/log/tomcat/catalina.out | grep -A10 -B10 -m1 "INFO: Server" | tac

Some notes:

  • You have probably guessed tac is the cat command backwards ie. it cats the file from the end towards the beginning.
  • Pipe this into the grep with the options:
    • -A10 and -B10 = Give some context, 10 lines before and 10 lines after.
    • -m1 = This tells grep to stop after it has found 1 entry.
    • Have to use quotes as the text I am looking for has a space.
  • Pipe this into tac again to put it back in the right order.

One small annoyance with this new command is that because we are re-taccing the file we lose grep's colourisation feature.

I know, I said it was a small annoyance...

HTH

Back to GNU/Linux Command Line Tips