bash 在 shell 脚本的最后 n 行中搜索文件内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24254676/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
search file content in last n lines of shell script
提问by Andy
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.
我使用命令 grep 文件内容,并做一些事情。
但是,文件大小每秒都在持续增长。(将大于 500MB)
由于性能问题,我想在最后 N 行而不是整个文件内容中 grep 文件内容。
if grep -q "SOMETHING" "/home/andy/log/1.log"; then
ps -ef | grep "127.0.0.1:50000" | awk '{print }' | 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!
如何修改脚本以在最后 N 行中 grep 文件内容?
谢谢!
回答by John C
you can use tail -n to get the last n lines of a file.
您可以使用 tail -n 获取文件的最后 n 行。
So you if you wanted to look only at the last 100 lines you could make your script work like this:
所以如果你只想查看最后 100 行,你可以让你的脚本像这样工作:
if tail -n 100 "/home/andy/log/1.log" | grep -q "SOMETHING"; then
...
回答by glenn Hymanman
Another approach is to compare the file size now versus the past and use tail -c
to get the difference in characters (bytes)
另一种方法是比较现在与过去的文件大小,并用于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
This way you're more certain that you're not missing anything, or grepping too much.
通过这种方式,您可以更确定自己没有遗漏任何东西,也没有太多的 grepping。