Linux

awk 中的 shell 變數沒有被傳遞給所有行,而只是用於輸入的第一行?

  • November 13, 2016

輸入文件:is2.txt

10.39.5.41,A1,B1
10.39.5.41,A2,B2
10.39.5.41,A3,B3
10.39.5.41,A4,B4
10.39.5.41,A5,B5
10.39.5.41,A6,B6

腳本 :

#!/bin/bash
second_column="OOOOOOO"    # OOOOOOO will be added to every second column
third_column="XXXXXXXX"    # XXXXXXXX will be added to every third column

awk -v second="$second_column" -v third="$third_column" 'BEGIN { FS="," }
                            {
                               if(a[$1])
                               {a[$1]=a[$1]";second"$2";third"$3}
                                else
                               {a[$1]=a[$1]second$2";"third$3}}
                            END{for (i in a)print i";"a[i];}' <  is2.txt

output:
[root@testgfs2 test]# ./testawk.awk
10.39.5.41;OOOOOOOA1;XXXXXXXXB1;secondA2;thirdB2;secondA3;thirdB3;secondA4;thirdB4;secondA5;thirdB5;secondA6;thirdB6

為什麼shell變數(second_column,third_column)沒有反映在完整的輸出中,而只是第一行。怎麼了?

預期輸出:

10.39.5.41;OOOOOOOA1;XXXXXXXXB1;OOOOOOOA2;XXXXXXXXB2;OOOOOOOA3;XXXXXXXXB3;OOOOOOOA4;XXXXXXXXB4;OOOOOOOA5;XXXXXXXXB5;OOOOOOOA6;XXXXXXXXB6

此外,有沒有什麼方法可以將這個概括為 n 列,比如 n = 100?

這是推薦的間距和縮進的awk程式碼,你能看出問題嗎?

BEGIN { FS = "," }

{
 if(a[$1])
   a[$1] = a[$1] ";second" $2 ";third" $3
 else
   a[$1] = a[$1]second $2 ";" third$3
}

END {
 for (i in a)
   print i ";" a[i]
}

你在子句中引用了second和。third``if

根據您的預期輸出猜測,您可以這樣做:

awk -v c2='OOOOOOO' -v c3='XXXXXXXX' -v FS=, -v OFS=';' -v ORS=';' '
 !f { 
   printf "%s", $1
   f=1
 } 
 {
   $1 = ""
   $2 = c2 $2
   $3 = c3 $3
 } 
 1
' | sed 's/;;/;/g; s/;$//'

輸出:

10.39.5.41;OOOOOOOA1;XXXXXXXXB1;OOOOOOOA2;XXXXXXXXB2;OOOOOOOA3;XXXXXXXXB3;OOOOOOOA4;XXXXXXXXB4;OOOOOOOA5;XXXXXXXXB5;OOOOOOOA6;XXXXXXXXB6

為了概括這種方法,您可以傳入位以預先通過字元串並將其拆分為 awk 數組。然後使用 for 循環而不是顯式列變數:

awk -v prepends='OOOOOOO XXXXXXXX' -v FS=, -v OFS=';' -v ORS=';' '
 BEGIN { split(prepends, cn, / +/) } 

 !f { 
   printf "%s", $1
   f=1
 } 

 { 
   $1 = ""
   for(i=1; i<=NF; i++) 
     $i = cn[i-1] $i
 }
 1' | sed 's/;;/;/g; s/;$//'

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