sha*_*nuo 5 shell pipe cat tee
我需要从日志文件中选择某些行并将它们保存到文本文件中。我尝试了以下操作,但没有一个按预期工作。文件“todel.txt”显示为 0 字节。
tail -f general.log | grep Some_word > >(tee -a todel.txt)
tail -f general.log | grep Some_word ; tee todel.txt
tail -f general.log | grep Some_word | tee -a todel.txt
Run Code Online (Sandbox Code Playgroud)
您需要添加stdbuf(1)
到您的管道中:
tail -f general.log | stdbuf -oL grep Some_word | tee -a todel.txt
Run Code Online (Sandbox Code Playgroud)
这会将grep
的 stdout 流缓冲模式设置为行缓冲,否则grep
等待从流中获取至少 4096 个字节(这是 Linux 上缓冲 i/o 的默认值)。
另外,您也可以拨打grep
同--line-buffered
:
tail -f general.log | grep --line-buffered Some_word | tee -a todel.txt
Run Code Online (Sandbox Code Playgroud)
有关详细说明,请参阅关闭管道中的缓冲和http://www.pixelbeat.org/programming/stdio_buffering/。
假设您有权在当前目录中写入文件,第三个应该可以正常工作。
例如:tail -f general.log | grep "Some_word" | tee todel.txt
这是正确定义的 tee 语法。如果它不起作用,那么你就做错了其他事情。
另外,最好将搜索字符串放在引号中。如果当前工作目录中有与搜索字符串匹配的文件名,则它可能被视为文件参数而不是搜索字符串。