BASH:AWK 将 CSV 转入所需的表

BASH:AWK 将 CSV 转入所需的表

我一直在努力使用 bash 将 .csv 文件转换为所需的表格式。

我的文件o/p:

$ cat finalcount.csv
state,status,count
NW,CONGESTED,11
NW,CLEARED,9
ACT,CLEARED,7
ACT,CONGESTED,7
QLD,CLEARED,5
WA,CONGESTED,3
WA,CLEARED,2
VIC,CLEARED,3
VIC,CONGESTED,2

我想要的o/p:

State   Congested  Cleared
ACT     7          7
NW      11         9
VIC     2          3
QLD     -          5

请分享您的答案并进行解释。

答案1

使用磨坊主

$ mlr --icsvlite --opprint \
    reshape -s status,count then unsparsify then reorder -e -f CLEARED finalcount.csv
state CONGESTED CLEARED
NW    11        9
ACT   7         7
QLD   -         5
WA    3         2
VIC   2         3

GNU 数据整合对于数据透视表(又名交叉表)之类的东西也很方便,尽管似乎没有任何简单的方法来控制列顺序:

datamash --header-in --filler=- -t, crosstab 1,2 unique 3 < finalcount.csv | csvformat -T
         CLEARED  CONGESTED
ACT      7          7
NW       9          11
QLD      5          -
VIC      3          2
WA       2          3

如果你确实需要使用 Awk,那么这样的东西应该可以工作:

awk -F, '
  NR>1 {s[$1]} 
  $2 == "CONGESTED" {a[$1]=$3} 
  $2 == "CLEARED" {b[$1]=$3} 
  END {
    printf "state\tcongested\tcleared\n"; 
    for (k in s) 
      printf "%s\t%s\t%s\n", k, a[k]=="" ? "-" : a[k], b[k]=="" ? "-" : b[k]      
  }
' finalcount.csv

答案2

$ cat tst.awk
BEGIN { FS=","; OFS="\t" }
{ sub(/\r$/,"") }
NR > 1 {
    states[$1]
    statuses[$2]
    vals[$1,$2] = $NF
}
END {
    printf "%s", "state"
    for (status in statuses) {
        printf "%s%s", OFS, status
    }
    print ""

    for (state in states) {
        printf "%s", state
        for (status in statuses) {
            printf "%s%s", OFS, ((state,status) in vals ? vals[state,status] : "-")
        }
        print ""
    }
}

$ awk -f tst.awk file
state   CONGESTED       CLEARED
QLD     -       5
ACT     7       7
WA      3       2
NW      11      9
VIC     2       3

$ awk -f tst.awk file | column -s $'\t' -t
state  CONGESTED  CLEARED
QLD    -          5
ACT    7          7
WA     3          2
NW     11         9
VIC    2          3

相关内容