Linux 从 tail -f 输出管道到 grep 后写入文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5341297/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 03:17:50  来源:igfitidea点击:

write to a file after piping output from tail -f through to grep

linuxunixgreptailcentos5

提问by Reddy

I'm looking to write to a file after piping output from tail -f through to grep. Say,write to a file "temp" for all lines with "Playing:" within in error_log "FreeSwitch.log".

我希望在将 tail -f 的输出通过管道传输到 grep 后写入文件。比如说,将 error_log “FreeSwitch.log”中带有“Playing:”的所有行写入文件“temp”。

 tail -f "/var/lof/freeswitch/freeswitch.log" | grep "Playing:" > temp

but not working ! It is a centos 5.5

但不工作!这是一个centos 5.5

回答by John Kugelman

Did you put the file name after the >?

你把文件名放在了之后>吗?

tail -f /var/lof/freeswitch/freeswitch.log | grep "Playing:" > temp

回答by Sergey

-f, --follow[={name|descriptor}]
              output appended data as the file grows;

It scans the file as it grows. And it is a process with an interval. You can only interrupt it.

它随着文件的增长而扫描文件。这是一个有间隔的过程。你只能打断它。

Use parameter:

使用参数:

-c, --bytes=K
              output the last K bytes; alternatively, use -c +K to output bytes starting with the Kth of each file  

or

或者

-n, --lines=K
              output the last K lines, instead of the last 10; or use -n +K to output lines starting with the Kth

EDIT: as bmk said:

编辑:正如 bmk 所说:

grep --line-buffered  

think it will help you

认为它会帮助你

回答by bmk

Maybe you have an issue with buffering? See BashFAQ: What is buffering?

也许你有缓冲问题?请参阅BashFAQ:什么是缓冲

You could e.g. try:

你可以尝试:

tail -f /var/lof/freeswitch/freeswitch.log | grep --line-buffered "Playing:" > temp

回答by BX16Soupapes

thanks for your help.

谢谢你的帮助。

here is my code to insert into mysql with the word "error":

这是我用“错误”一词插入 mysql 的代码:

tail -f /var/log/httpd/error_log | \
grep -E --line-buffered "error" | \
while read line; do \
#echo -e "MY LINE: ${line}"; done
echo "INSERT INTO logs (logid,date,log) VALUES (NULL, NOW(), '${line}');" | mysql -uUSERDB -pPASSDB DBNAME; done