bash 在 awk 中使用 grep 就像条件一样
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24834206/
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
using grep as if condition inside awk
提问by user1739455
I can use grep -Fxq search-string text-file
outside of my awk, and it works they way I'd expect (found here How to test if string exists in file with Bash shell?). But, when I try to use that same grep command as an if statement inside awk, it seems to do nothing. Here's the basic usage I'm trying:
我可以grep -Fxq search-string text-file
在我的 awk 之外使用,它以我期望的方式工作(在此处找到如何使用 Bash shell 测试文件中是否存在字符串?)。但是,当我尝试在 awk 中使用相同的 grep 命令作为 if 语句时,它似乎什么也没做。这是我正在尝试的基本用法:
cat /var/log/somelogfile | awk '{ if (grep -Fxq textfile) print "useful command " }'
采纳答案by djhaskin987
回答by Ed Morton
It LOOKS like what you're trying to do is:
看起来你想要做的是:
awk '
NR==FNR { strings[ perl -ne 'if (/some line (.*)/) {print "useful command: \n"}' /var/log/somelogfile
]; next }
{
for (string in strings) {
if ( index(##代码##,string) ) {
print "useful command",
next
}
}
}
' textfile /var/log/somelogfile
We'll know for sure if/when you post some some sample input/output.
我们会确定您是否/何时发布一些示例输入/输出。
回答by Tiago Lopo
There is no need for that, you can use anchors:
没有必要,您可以使用锚点:
awk '/^search-string$/ {do something}'
awk '/^search-string$/ {do something}'
Explanation:
解释:
^
Beginning of the line$
End of line/^search-string$/
return true if matches just likegrep -Fxq
^
行的开头$
行结束/^search-string$/
如果匹配就返回真grep -Fxq
-x
for grep uses anchors. I believe -F
is redundant.
-x
对于 grep 使用锚点。我相信-F
是多余的。
回答by Jakub M.
If grep
or egrep
are insufficient for your text filtering, it might be easier to a perl one liner. perl
offers useful command line options, like -n -e
which will implicitly executes your arbitrary command inside while
loop.
如果grep
或egrep
不适合您的文本过滤,使用 perl one liner 可能会更容易。perl
提供有用的命令行选项,例如-n -e
将在while
循环内隐式执行您的任意命令。
So for example:
例如:
##代码##will filter all the lines with "some line" text and will print everything after that text.
将过滤所有带有“某行”文本的行,并打印该文本之后的所有内容。