我正在使用“tail -f”来跟踪更新的日志文件;接下来我将它的输出通过管道传递给 grep 以仅显示包含搜索词的行(在本例中为“org.springframework”);最后我想做的是将 grep 的输出通过管道传递给第三个命令“cut”:
tail -f logfile | grep org.springframework | cut -c 25-
如果 cut 命令可以从 grep 获取输入,它会为我删除每行的前 25 个字符!(如果我从链中删除“grep”,它会按预期工作。)
我将 cygwin 与 bash 结合使用。
实际结果:当我添加第二个管道以连接到“cut”命令时,结果是它挂起,就好像它在等待输入(如果您想知道的话)。
最佳答案
假设使用 GNU grep,将 --line-buffered
添加到您的命令行,例如。
tail -f logfile | grep --line-buffered org.springframework | cut -c 25-
编辑:
我看到 grep 缓冲不是这里唯一的问题,因为 cut 不允许按行缓冲。
您可能想尝试用您可以控制的东西替换它,例如 sed:
tail -f logfile | sed -u -n -e '/org\.springframework/ s/\(.\{0,25\}\).*$/\1/p'
或 awk
tail -f logfile | awk '/org\.springframework/ {print substr($0, 0, 25);fflush("")}'
关于bash - 您如何通过 grep 将输入管道传输到另一个实用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/972370/