Reputation: 6395
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
.
Upvotes: 2
Views: 5979
Reputation: 290515
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.
Upvotes: 4
Reputation: 16586
Instead of tail
, use tac
. It will reverse the file and you can exit when you first grep something:
tac "$log" | awk '$9 ~ "'$something'" {print $0;exit}'
Upvotes: 2
Reputation: 31349
tac $FILE | grep $SOMETHING -m 1
tac
: the reverse of cat
:-)
grep -m
: search and stop on first occurrence
Upvotes: 2
Reputation: 7351
tail -1000
takes only the last 1000 lines from your file.
You could grep that part, but you wouldn't know if the thing you grep for occurred in the earlier lines. There's no way to grep "backwards".
Upvotes: 1