[英]How to use shell to continuously process tail -f new lines in real time?
linux服务器上有一个文件,该文件中不定期添加新行。 我需要处理新行,对其进行解析,并使用其他命令或脚本对其进行处理。 定期检查文件是不可接受的,我需要实时解决方案。 服务器上没有其他语言(Python,Perl)可用,只有外壳程序可用。
现在,我试图将新行分配给shell变量,然后对其进行处理。 但是找不到一个好的方法。 另一个问题是在处理新行时,我需要依靠某些结果前者。 例如,当我处理第11行时,可能需要第5行结果。 因此,之前需要存储结果的一些变量,我需要在循环中使用它们。
对我的情况有任何解决方案或更好的建议吗?
试试下面的代码
#!/bin/bash
process_new_line() {
local var= '' #declare some local variables here
read
while true
do
#process $REPLY
#The new line content is in the variable $REPLY
#store the result in the local variable according to your rules.
read
done
}
tail -f the_file | process_new_line
使用功能将解决您的问题。 您可以使用局部变量存储结果,而$ REPLY保留新行内容。
尝试:
tail -f filename | while read -r line; do
: # process the line
done
这是实时的,除非缓冲了行。 如果缓冲使您stdbuf
困扰,则可以使用诸如stdbuf
类的实用程序来缩小缓冲区。
您没有提到您的系统是否有awk。 Unix系统的POSIX标准需要它。 如果有,它非常适合“计算,替换某些字符”等:
tail -f filename | awk 'awk code'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.