这是我在脚本中用于grep实时数据的命令。它似乎没有正确提取实时数据,因为它只是错过了一些行。
tail -f <file> | fgrep "string" | sed 's/stuff//g' >> output.txt
Run Code Online (Sandbox Code Playgroud)
下面的命令会做什么?什么是“行缓冲”?
tail -f <file> | fgrep --line-buffered "string" | sed 's/stuff//g' >> output.txt
Run Code Online (Sandbox Code Playgroud)
cuo*_*glm 53
以非交互方式使用时,大多数标准命令 include 会grep缓冲输出,这意味着它不会立即将数据写入stdout. 它在写入之前收集大量数据(取决于操作系统,在 Linux 中,通常为 4096 字节)。
在您的命令中,grep的输出通过管道传送到stdinofsed命令,因此grep缓冲其输出。
因此,--line-buffered选项导致grep使用行缓冲区,这意味着每次看到换行符时都会写入输出,而不是默认等待达到 4096 字节。但在这种情况下,您根本不需要grep,只需使用tail+ sed:
tail -f <file> | sed '/string/s/stuff//g' >> output.txt
Run Code Online (Sandbox Code Playgroud)
使用没有选项修改缓冲区的命令,您可以使用GNU coreutils stdbuf
tail -f <file> | stdbuf -oL fgrep "string" | sed 's/stuff//g' >> output.txt
Run Code Online (Sandbox Code Playgroud)
打开行缓冲或使用-o0禁用缓冲区。
笔记