grep 显示所有行,而不仅仅是匹配,设置退出状态
我正在将命令的一些输出传输到egrep,我用它来确保特定的失败字符串不会出现在其中。
不幸的是,命令本身不会在失败时返回正确的非零退出状态,这就是我这样做的原因。
command | egrep -i -v "badpattern"
这只要给我想要的退出代码即可(如果输出中出现错误模式则为 1,否则为 0),但是,它只会输出与模式不匹配的行(正如 -v 开关的设计目的) )。对于我的需求来说,这些线路是最有趣的线路。
有没有办法让 grep 盲目地传递它作为输入获得的所有行,并根据需要给出退出代码?
如果没有,我想我可以使用 perl -ne "print; exit 1 if /badpattern/"。我使用 -n 而不是 -p,因为 -p 不会打印有问题的行(因为它在运行单行代码后打印)。因此,我使用 -n 并自己调用 print
,这至少给了我第一条有问题的行,但随后输出(和执行)在那里停止,所以我必须执行类似
的操作perl -e '$code = 0; while (<>) { 打印; $code = 1 if /badpattern/; } exit $code'
它完成了整个交易,但是有点多,是否有一个简单的 grep 命令行开关可以完成我正在寻找的事情?
I'm piping some output of a command to egrep, which I'm using to make sure a particular failure string doesn't appear in.
The command itself, unfortunately, won't return a proper non-zero exit status on failure, that's why I'm doing this.
command | egrep -i -v "badpattern"
This works as far as giving me the exit code I want (1 if badpattern appears in the output, 0 otherwise), BUT, it'll only output lines that don't match the pattern (as the -v switch was designed to do). For my needs, those lines are the most interesting lines.
Is there a way to have grep just blindly pass through all lines it gets as input, and just give me the exit code as appropriate?
If not, I was thinking I could just use perl -ne "print; exit 1 if /badpattern/". I use -n rather than -p because -p won't print the offending line (since it prints after running the one-liner). So, I use -n and call print
myself, which at least gives me the first offending line, but then output (and execution) stops there, so I'd have to do something like
perl -e '$code = 0; while (<>) { print; $code = 1 if /badpattern/; } exit $code'
which does the whole deal, but is a bit much, is there a simple command line switch for grep that will just do what I'm looking for?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
其实你的perl想法还不错。尝试:
我敢打赌这至少与建议的其他选项一样快。
Actually, your perl idea is not bad. Try:
I bet this is at least as fast as the other options being suggested.
如何重定向到 /dev/null ,从而删除所有行,但仍然得到退出代码?
或者您可以简单地使用
-q
开关How about doing a redirect to /dev/null, hence removing all lines, but you still get the exit code?
Or you can simply use the
-q
switch