簡體   English   中英

如何使用awk比較CSV列?

[英]How to Compare CSV Column using awk?

我收到這樣的CSV:

column$1,column$2,column$
john,P,10
john,P,10
john,A,20
john,T,30
john,T,10
marc,P,10
marc,C,10
marc,C,20
marc,T,30
marc,A,10

我需要對這些值求和並顯示名稱和結果,但是$ 2列需要顯示與值P,A,C分開的值T的總和。 輸出應為:

column$1,column$2,column$3,column$4
john,PCA,40
john,T,40,CORRECT
marc,PCA,50
marc,T,30,INCORRECT

我所能做的就是從原始csv中提取我需要的列:

    awk -F "|" '{print $8 "|" $9 "|" $4}' input.csv >> output.csv

還要按正確的列排序:

sort -t "|" -k1 input.csv >> output.csv

並將新列添加到csv的末尾:

awk -F, '{NF=2}1' OFS="|" input.csv >> output.csv

我設法按列$ 1和$ 2求和並顯示總和,但是我不怎么對列$ 2中的不同值進行分組:

awk -F "," '{col[$1,$2]++} END {for(i in col) print i, col[i]}' file > output

Awk是面向流的。 它處理輸入並輸出您所做的更改。 它在文件更改中不起作用。

您只需要添加相應的打印

awk '{if($2 == "T") {print "MATCHED"}}'

如果要輸出比“ matched”更多的內容,則需要將其添加到打印內容中,例如'{print $1 "|" $2 "|" $3 "|" " MATCHED"}' '{print $1 "|" $2 "|" $3 "|" " MATCHED"}'

或使用print $0作為上述評論。

假設通過將“ PCA”值與“ T”值進行比較來確定“ CORRECT”和“ INCORRECT”,則以下awk腳本應該可以解決問題:

awk -F, -vOFS=, '$2=="T"{t[$1]+=$3;n[$1]} $2!="T"{s[$1]+=$3;n[$1]} END{ for(i in n){print i,"PCA",s[i]; print i,"T",t[i],(t[i]==s[i] ? "CORRECT" : "INCORRECT")} }' inputfile

分解以方便閱讀,這是這樣的:

awk -F, -vOFS=, '

  $2=="T" {    # match all records that are "T"
    t[$1]+=$3  # add the value for this record to an array of totals
    n[$1]      # record this name in our authoritative name list
  }

  $2!="T" {    # match all records that are NOT "T"
    s[$1]+=$3  # add the value for this record to an array of sums
    n[$1]      # record this name too
  }

  END {        # Now that we've collected data, analyse the results
    for (i in n) {  # step through our authoritative list of names
      print i,"PCA",s[i]
      print i,"T",t[i],(t[i]==s[i] ? "CORRECT" : "INCORRECT")
    }
  }

' inputfile

請注意,數組順序不能以awk保證,因此輸出的順序可能與輸入的順序不同。

如果要使用豎線分隔輸出,請將-vOFS=,更改為-vOFS='|'

然后,您可以使用以下命令進行排序:

awk ... | sort

默認為-k1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM