[英]Interactively piping through grep
I have a script which takes fairly long to execute. 我有一个脚本需要相当长的时间来执行。 Throughout the process, it is continuously outputing to stdout.
在整个过程中,它不断输出到stdout。 I would like to have some of these mesages interactively displayed in some sort of progress dialog using a graphical utility like kdialog or zenity for instance, but that's not relevant here, for the solution I seek should not depend on it.
我想在某些进度对话框中使用kdialog或zenity之类的图形工具以交互方式显示这些消息中的一些,但这在这里不相关,因为我寻求的解决方案不应该依赖于它。
To accomplish this I'm trying the following 为了实现这一点,我正在尝试以下方法
<call to actual job> | egrep <regex> | xargs -I{} <call to display utility> {}
The problem is that once I insert the call to egrep
the output is sort of accumulated untill the main job finishes, before it is effectively piped on to xargs
. 问题是,一旦我将调用插入
egrep
,输出就会累积,直到主要作业完成,然后才能有效地传输到xargs
。 If I take egrep
out, then it works as expected and the status mesages are interactively piped on to xargs
, but then a lot of irelevant information is displayed. 如果我取出
egrep
,那么它按预期工作,并且状态消息以交互方式传送到xargs
,但随后会显示许多相关信息。
I've been searching all over the internet and reading the manual for grep
to no avail, does anyone know how I could achieve the desired behavior? 我一直在网上搜索并阅读
grep
手册无济于事,有谁知道我怎么能达到理想的行为?
Practical Example 实际例子
I believe the following example behaves analogously to my real case. 我相信以下示例与我的实际情况类似。
(sleep 1; echo A; sleep 1; echo 0; sleep 1; echo B) | egrep -i [a-z] | xargs -I{} echo {}
Try to use a less buffered command. 尝试使用less buffered命令。 I'm not sure about awk but you could do this with it:
我不确定awk但你可以用它做到这一点:
<call to actual job> | awk '/regex/' | xargs -I{} <call to display utility> {}
Another with sed: 另一个用sed:
<call to actual job> | sed -n '/regex/p' | xargs -I{} <call to display utility> {}
And my favorite for that actually would be bash: 而我最喜欢的就是bash:
function filter {
while read -r __; do
[[ $__ =~ $1 ]] && echo "$__"
done
}
<call to actual job> | filter "<regex>" | xargs -I{} <call to display utility> {}
It's could be a little slower but it certainly doesn't buffer output much. 它可能会慢一点,但它肯定不会缓慢输出。
Meanwhile I found the exact answer this question: grep
and its variations have an option to force flushing line by line. 与此同时,我找到了这个问题的确切答案:
grep
及其变体可以选择逐行强制冲洗。
man is not very helpful 男人不是很有帮助
--line-buffered Use line buffering on output.
--line-buffered在输出上使用行缓冲。 This can cause a performance penalty.
这可能会导致性能下降。
that's why I overlooked this option at first. 这就是我最初忽略这个选项的原因。
Fortunately grep --help
makes it more obvious. 幸运的是,
grep --help
让它变得更加明显。
--line-buffered flush output on every line
-每行上的 - line -buffered flush输出
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.