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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 10:55:01  来源:igfitidea点击:

using grep as if condition inside awk

linuxbashawkgrep

提问by user1739455

I can use grep -Fxq search-string text-fileoutside 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

You can use awk's systemfunction:

您可以使用 awk 的system功能:

cat /var/log/somelogfile | awk '{ if (system("grep -Fxq "  " textfile")) print "useful command " ; }'

See the docs.

请参阅文档

回答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:

解释:

  1. ^Beginning of the line
  2. $End of line
  3. /^search-string$/return true if matches just like grep -Fxq
  1. ^行的开头
  2. $行结束
  3. /^search-string$/如果匹配就返回真 grep -Fxq

-xfor grep uses anchors. I believe -Fis redundant.

-x对于 grep 使用锚点。我相信-F是多余的。

回答by Jakub M.

If grepor egrepare insufficient for your text filtering, it might be easier to a perl one liner. perloffers useful command line options, like -n -ewhich will implicitly executes your arbitrary command inside whileloop.

如果grepegrep不适合您的文本过滤,使用 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.

将过滤所有带有“某行”文本的行,并打印该文本之后的所有内容。