Awk 在转置期间处理不存在的条目
我有一个数据文件,需要在awk中进行转置处理不存在的值Awk 在转置期间处理不存在的条目,awk,git-bash,Awk,Git Bash,我有一个数据文件,需要在awk中进行转置处理不存在的值 id|type|cost|date|ship 0|A|223|201603|PORT 0|A|22|201602|PORT 0|A|422|201601|DOCK 1|B|3213|201602|DOCK 1|B|3213|201601|PORT 2|C|2321|201601|DOCK 我需要进行转换,并将输出作为 id|type|201601|201602|201603| 0|A|422.0|22.0|223.0| 1|B|3213.
id|type|cost|date|ship
0|A|223|201603|PORT
0|A|22|201602|PORT
0|A|422|201601|DOCK
1|B|3213|201602|DOCK
1|B|3213|201601|PORT
2|C|2321|201601|DOCK
我需要进行转换,并将输出作为
id|type|201601|201602|201603|
0|A|422.0|22.0|223.0|
1|B|3213.0|3213.0|n/a|
2|C|2321.0|n/a|n/a|
我正在awk中尝试pivot,但它不起作用
awk -F"|" -v OFS="|" ' NR>1 { k=$1 OFS $2;id[k]++;date[$4]++;cost[k]=$3 } END {printf("%s","id|type|");for(i in date) printf("%s|",i);print ""; for(i in id) { printf("%s|",i); for(j in date) { if( (i) in cost) { printf("%s|", cost[i OFS j]);} else { printf("%s|","n/a")} } print "" } } ' data.txt
只是印刷而已
id|type|201601|201602|201603|
0|A||||
1|B||||
2|C||||
您可以试试这个
gnu awk
:
awk'BEGIN{FS=OFS=“|”;PROCINFO[“sorted_in”]=“@ind_stru asc”}NR>1{hdr[$1 of s$2][$4]=$3}END{printf“%s”,“id”of s“type”of s;对于(i在hdr中)printf“%s”,i of s;print“”;对于(r在map中){printf“%s”,r of s,r of s;(i在hdr中)printf s%s“,”,(map[r][i]:OFS],[sprint];printf i],[sprint]
id |类型| 201601 | 201602 | 201603|
0 | A | 422.0 | 22.0 | 223.0|
1 | B | 3213.0 | 3213.0 |不适用|
2 | C | 2321.0 |不适用|不适用|
更具可读性的awk
:
awk'开始{
FS=OFS=“|”
PROCINFO[“排序在”]=“@ind\u str\u asc”
}
NR>1{
hdr[$4]
地图[$1/s$2][$4]=$3
}
结束{
#打印页眉
printf“%s”,“id”of s“type”of s
用于(hdr中的i)
printf“%s”,i of s
打印“”
#印刷体
用于(地图中的r){
printf“%s”,r of s
用于(hdr中的i)
printf“%s%s”,(映射[r][i]=“”?“不适用”:sprintf(“.1f”,映射[r][i]),OFS
打印“”
}
}"档案"