Awk

如果條件錯誤則 awk

  • December 23, 2020

我寫了一個 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

你錯過了兩個),或者一個),然後有一個(太多。

更正的程式碼(刪除了多餘的括號;此處的換行符僅用於說明,實際上不會執行):

{
       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))
}

引用自:https://unix.stackexchange.com/questions/625742