Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

search file content in last n lines of shell script


I use the command the grep file content, and do something.
However, the file size is growing continuous every second. (will larger than 500MB)
Due to the performance issue, I want to grep file content in last N lines rather than entire file content.

if grep -q "SOMETHING" "/home/andy/log/1.log"; then
    ps -ef | grep "127.0.0.1:50000" | awk '{print $2}' | xargs kill; cat /dev/null > /home/andy/log/1.log
fi

How can I modify the script to grep file content in last N lines?
Thanks!

like image 813
Andy Avatar asked Jun 17 '14 02:06

Andy


1 Answers

you can use tail -n to get the last n lines of a file.

So you if you wanted to look only at the last 100 lines you could make your script work like this:

if tail -n 100 "/home/andy/log/1.log" | grep -q "SOMETHING"; then
...
like image 53
John C Avatar answered Sep 24 '22 12:09

John C