awk if 条件错误

awk if 条件错误

我写了一个 awk 命令,它根据条件进行过滤

awk '{if(( (substr($0,9,3) == "TGO") &&  ((substr($0,1,4) == "9123" || (substr($0,1,4) == "9704"))) print (substr($0,279,2),substr($0,1,4),substr($0,5,8));}' Downloadfinance.txt

这是一个语法错误。我尝试了多种方法,但仍然抛出相同的异常。

这是错误

awk: cmd. line:1: {if(( (substr($0,9,3) == "TGO") &&  ((substr($0,1,4) == "9123" || (substr($0,1,4) == "9704"))) print (substr($0,9,3),substr($0,1,4),substr($0,5,8));}
awk: cmd. line:1:                                                                                                 ^ syntax error
awk: cmd. line:1: {if(( (substr($0,9,3) == "TGO") &&  ((substr($0,1,4) == "9123" || (substr($0,1,4) == "9704"))) print (substr($0,9,3),substr($0,1,4),substr($0,5,8));}
awk: cmd. line:1:                                                                                                                                                       ^ syntax error

答案1

您缺少两个),或者缺少一个,然后又缺少)一个。(

更正的代码(删除了多余的括号;这里的换行符仅用于说明,这实际上不会运行):

{
        if (
                substr($0,9,3) == "TGO" &&
                (
                        substr($0,1,4) == "9123" || substr($0,1,4) == "9704"
                )
        )
                print substr($0,279,2), substr($0,1,4), substr($0,5,8)
}

或者(对于换行符的位置,此语法是正确的)

{
        if (substr($0,9,3) == "TGO" && (substr($0,1,4) == "9123" || substr($0,1,4) == "9704" ))
                print substr($0,279,2), substr($0,1,4), substr($0,5,8)
}

或(使用模式动作机制)

substr($0,9,3) == "TGO" && (substr($0,1,4) == "9123" || substr($0,1,4) == "9704") {
        print substr($0,279,2), substr($0,1,4), substr($0,5,8)
}

您的代码格式与上面第一个变体相同,但所有括号都完好无损:

{
        # too many ( below
        if ((
                (substr($0,9,3) == "TGO") &&
                (
                        # missing ) below, alt. too many ( and )
                        (substr($0,1,4) == "9123" || (substr($0,1,4) == "9704")
                )
        )
                print (substr($0,279,2),substr($0,1,4),substr($0,5,8))
}

答案2

我不能确定,因为你还没有给我们一个要测试的文件,但我猜这就是你想要写的:

awk '{ if( substr($0,9,3) == "TGO" && (substr($0,1,4) == "9123" || substr($0,1,4) == "9704")){ print substr($0,279,2),substr($0,1,4),substr($0,5,8)}}' Downloadfinance.txt

或者,更清晰一点:

awk '{ 
        if( substr($0,9,3) == "TGO" && 
            (substr($0,1,4) == "9123" || substr($0,1,4) == "9704")){ 
                print substr($0,279,2),substr($0,1,4),substr($0,5,8)
            }
    }' Downloadfinance.txt

答案3

或者,您可以将if条件移至规则前提条件:

awk  'substr($0,9,3) == "TGO"  && (substr($0,1,4) == "9123" || substr($0,1,4) == "9704"){
                print substr($0,279,2),substr($0,1,4),substr($0,5,8)
              }'

您还可以将其简化为:

awk 'substr($0,9,3) == "TGO"  && (/^9123/ || /^9704/) { print .... }'

答案4

如果你使用GNUawk(或可以)它有一个特点直接处理这个问题:

awk -vFIELDWIDTHS="4 4 3 267 2" '$3=="TGO" && ($1=="9123"||$1=="9704"){ print $5,$1,$2 }'

相关内容