bash `and` 和 `or` 在一个 awk 命令中的多个条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42096063/
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 15:43:38  来源:igfitidea点击:

multiple conditions of `and` and `or` in one awk command

bashawk

提问by user7352907

I am trying to use multiple 'AND' and 'OR' condition in awk but it is not giving me the desired output. Instead it doesn't read the last &&conditions that i have given with time '030000'.

我试图在 awk 中使用多个“AND”和“OR”条件,但它没有给我想要的输出。相反,它不会读取&&我在时间“030000”时给出的最后条件。

awk -F, '{if(substr(,1,3)=="301" && =="996" || =="429" && >=030000 && <=035000) print "|""|"}' 2017020* | head -10

3014241320|996|235939
3017943809|996|235953

采纳答案by hek2mgl

Looks like you missed parentheses around the ORoperation. It should be:

看起来您错过了OR操作周围的括号。它应该是:

if(substr(,1,3)=="301" && (=="996" || =="429") && >=030000 && <=035000) ...

See boolean algebra.

请参阅布尔代数

回答by aferber

In awk, &&has higher precedence than ||, so your condition actually means

在 awk 中,&&优先级高于||,因此您的条件实际上意味着

    (substr(,1,3)=="301" && =="996")
||
    (=="429" && >=030000 && <=035000)

Your tests for $5are only applied to lines where $15=="429"is true, which isn't the case in your example output lines.

您的测试$5仅适用于$15=="429"为真的行,而在您的示例输出行中并非如此。

Use parentheses to change that:

使用括号来改变它:

awk -F, '{if(substr(,1,3)=="301" && (=="996" || =="429") && >=030000 && <=035000) print "|""|"}' 2017020* | head -10

As a general rule, I would always parenthesize expressions with mixed logical AND and OR in any language even if not strictly necessary. This aids readability and avoids nasty surprises (there are languages out there with different precedence for AND and OR...).

作为一般规则,即使不是绝对必要的,我也会在任何语言中用混合的逻辑 AND 和 OR 将表达式括起来。这有助于提高可读性并避免令人讨厌的意外(有些语言对 AND 和 OR 具有不同的优先级......)。