Searching file contents in last n lines of shell script


I use the grep file content command and am doing something.
However, the file size grows continuously every second. (will be more than 500 MB)
Due to a performance problem, I want to grep the contents of the file in the last N lines, and not the contents of the entire file.

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 change the contents of a script to a grep file in the last N lines?
Thank!

+4
source share
2 answers

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

So, if you want to look only at the last 100 lines, you can make your script work like this:

if tail -n 100 "/home/andy/log/1.log" | grep -q "SOMETHING"; then
...
+8

tail -c ()

# prev_size is known
curr_size=$(stat -c %s file.log)
if tail -c $((curr_size - prev_size)) | grep -q pattern; then ...
    # ...
fi
prev_size=$curr_size
# loop

, , , .

+2

Source: https://habr.com/ru/post/1544833/


All Articles