輸入
[email protected]:/tmp$ cat data.txt
1,Brand,sports
1,Color,White
1,Gender,Male
1,Logo,yes
1,width,10
4,Brand,Running
4,width,12
4,Fits,Lose
3,catgegory,shoe
3,Color,blue
3,primarycolor,blue
5,size,M
5,Brand,Running
腳本
[email protected]:/tmp$ cat pivot.awk
{
id=$1; name=$2; value=$3
ids[id];
# this is to retain order
if(!(name in tmp)){ tmp[name]; names[++c]=name; }
values[id,name] = value
}
END {
# comment below line if you hide "id"
printf "id"
for (name in names) {
printf "%s%s",OFS,names[name]
}
print ""
for (id in ids) {
printf "%s",id
for (name in names) {
printf "%s%s",OFS,values[id,names[name]]
} print ""
}
}
執行和輸出
[email protected]:/tmp$ awk -v FS=, -v OFS=, -f pivot.awk data.txt
id,Brand,Color,Gender,Logo,width,Fits,catgegory,primarycolor,size
1,sports,White,Male,yes,10,,,,
3,,blue,,,,,shoe,blue,
4,Running,,,,12,Lose,,,
5,Running,,,,,,,,M
這產生O/P相同預期O/P包括訂單
[email protected]:/tmp$ cat pivot_with_order.awk
{
id=$1; name=$2; value=$3
# this is to retain order
if(!(id in itmp)){ itmp[id]; ids[++i]=id; }
if(!(name in tmp)){ tmp[name]; names[++c]=name; }
values[id,name] = value
}
END {
# uncomment below line if you want to display "id"
# printf "id"
for (name in names) {
printf "%s%s",OFS,names[name]
}
print ""
for (id in ids) {
printf "%s",ids[id]
for (name in names) {
printf "%s%s",OFS,values[ids[id],names[name]]
} print ""
}
}
輸出
[email protected]:/tmp$ awk -v FS=, -v OFS=, -f pivot_with_order.awk data.txt
,Brand,Color,Gender,Logo,width,Fits,catgegory,primarycolor,size
1,sports,White,Male,yes,10,,,,
4,Running,,,,12,Lose,,,
3,,blue,,,,,shoe,blue,
5,Running,,,,,,,,M
非常感謝阿克沙伊,我會很快檢查這一項。如果我有不同的充值,下同filed.like –
想,我怎樣才能改變腳本@akshay赫格德 5,品牌,運行 5,品牌,Running1 輸出: 5,跑步/ Running1 ,,, ,,,,, M –
對不起,我已經修改了問題以包含重複的方案。 –