Search code examples
bashawkgreptail

How to start from the last line with tail?


I have a huge log file. I need to find something and print last line. Like this:

tail -n +1 "$log" | awk '$9 ~ "'$something'" {print $0}' | tail -n1

But when I execute this command, tail starts from 1st line and reads all the lines. And running few mins.

How can I start to read from the last line and stop when I find something? So maybe I don't need to read all lines and running just few secs. Because I need just last line about $something.


Solution

  • Note you are saying tail -n +1 "$log", which is interpreted by tail as: start reading from line 1. So you are in fact doing cat "$log".

    You probably want to say tail -n 1 "$log" (without the + before 1) to get the last n lines.

    Also, if you want to get the last match of $something, you may want to use tac. This prints a file backwards: first the last line, then the penultimate... and finally the first one.

    So if you do

    tac "$log" | grep -m1 "$something"
    

    this will print the last match of $something and then exit, because -mX prints the first X matches.

    Or of course you can use awk as well:

    tac "$log" | awk -v pattern="$something" '$9 ~ pattern {print; exit}'
    

    Note the usage of -v to give to awk the variable. This way you avoid a confusing mixure of single and double quotes in your code.