保存另一个命令的输出

保存另一个命令的输出

我需要从日志文件中选择某些行并将它们保存到文本文件中。我尝试了以下方法,但没有一个按预期工作。文件“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

答案1

您需要添加stdbuf(1)到您的管道中:

tail -f general.log | stdbuf -oL grep Some_word | tee -a todel.txt

这会将grep的 stdout 流缓冲模式设置为行缓冲,否则grep等待从流中获取至少 4096 字节(这是 Linux 上缓冲 I/O 的默认设置)。

或者,您也可以grep通过以下方式致电--line-buffered

tail -f general.log | grep --line-buffered Some_word | tee -a todel.txt

关闭管道中的缓冲http://www.pixelbeat.org/programming/stdio_buffering/以获得详细解释。

答案2

假设您有权在当前目录中写入文件,那么第三个应该可以正常工作。

例如:tail -f general.log | grep "Some_word" | tee todel.txt

这是正确定义的 tee 语法。如果它不起作用,那么你就做错了其他事情。

另外,最好将搜索字符串放在引号中。如果当前工作目录中有与搜索字符串匹配的文件名,则它可能被视为文件参数而不是搜索字符串。

答案3

grep "my words" > mytextfile.txt
tail -f access.log > last_log.txt
tail -f access.log | grep "IP address" > hacker.log

答案4

您要查找的线路可能正在发送至标准错误而不是标准输出,在这种情况下,以 结束该行2>&1应该可以解决问题:

tail -f general.log | grep Some_word | tee -a todel.txt 2>&1

相关内容