bash 您如何通过 grep 将输入通过管道传输到另一个实用程序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/972370/
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
How do you pipe input through grep to another utility?
提问by les2
I am using 'tail -f' to follow a log file as it's updated; next I pipe the output of that to grep to show only the lines containing a search term ("org.springframework" in this case); finally I'd like to make is piping the output from grep to a third command, 'cut':
我正在使用“tail -f”来跟踪更新的日志文件;接下来我将其输出通过管道传递给 grep 以仅显示包含搜索词的行(在本例中为“org.springframework”);最后,我想将 grep 的输出通过管道传输到第三个命令“cut”:
tail -f logfile | grep org.springframework | cut -c 25-
The cut command would remove the first 25 characters of each line for me if it could get the input from grep!(It works as expected if I eliminate 'grep' from the chain.)
如果可以从 grep 获取输入,cut 命令将为我删除每行的前 25 个字符!(如果我从链中消除“grep”,它会按预期工作。)
I'm using cygwin with bash.
我在 bash 中使用 cygwin。
Actual results: When I add the second pipe to connect to the 'cut' command, the result is that it hangs, as if it's waiting for input (in case you were wondering).
实际结果:当我添加第二个管道以连接到 'cut' 命令时,结果是它挂起,好像在等待输入(以防万一)。
采纳答案by Paused until further notice.
On my system, about 8K was buffered before I got any output. This sequence worked to follow the file immediately:
在我的系统上,在我得到任何输出之前缓冲了大约 8K。此序列可以立即跟踪文件:
tail -f logfile | while read line ; do echo "$line"| grep 'org.springframework'|cut -c 25- ; done
回答by Hasturkun
Assuming GNU grep, add --line-buffered
to your command line, eg.
假设 GNU grep,添加--line-buffered
到您的命令行,例如。
tail -f logfile | grep --line-buffered org.springframework | cut -c 25-
Edit:
编辑:
I see grep buffering isn't the only problem here, as cut doesn't allow linewise buffering.
我看到 grep 缓冲不是这里唯一的问题,因为 cut 不允许逐行缓冲。
you might want to try replacing it with something you can control, such as sed:
您可能想尝试将其替换为您可以控制的内容,例如 sed:
tail -f logfile | sed -u -n -e '/org\.springframework/ s/\(.\{0,25\}\).*$//p'
or awk
或 awk
tail -f logfile | awk '/org\.springframework/ {print substr(##代码##, 0, 25);fflush("")}'
回答by Adam Rosenfield
What you have should work fine -- that's the whole idea of pipelines. The only problem I see is that, in the version of cut
I have (GNU coreutiles 6.10), you should use the syntax cut -c 25-
(i.e. use a minus sign instead of a plus sign) to remove the first 24 characters.
你所拥有的应该可以正常工作——这就是管道的全部思想。我看到的唯一问题是,在cut
我拥有的版本(GNU coreutiles 6.10)中,您应该使用语法cut -c 25-
(即使用减号而不是加号)来删除前 24 个字符。
You're also searching for different patterns in your two examples, in case that's relevant.
您还在两个示例中搜索不同的模式,以防万一。