如何在unix中转置或旋转文本文件的数据? [英] How to transpose or pivot data of a text file in unix?
问题描述
我在Unix中有一个输入文本文件,其中包含这种数据.
I have an input text file in unix with this kind of data.
Event_date:20190512044638
Error_code:5858
Event_type:GPRS data
Duration:772
Missing_provider_id:46009
Event_date:20190512044638
Error_code:780678
Event_date:20190512064535
Error_code:5858
Event_type:GPRS data
Duration:2172
Missing_provider_id:722310
我希望这些数据采用以下输出格式:
i want this data to be in this output format:
Event_date Error_code Event_type Duration Missing_provider_id
20190512044638 5858 GPRS data 772 46009
20190512044638 780678
20190512064535 5858 GPRS data 2172 722310
我尝试了awk和sed命令的组合,但是没有解决. 我如何获得此输出?
I tried a combination of awk and sed commands, but didn't work out. How can i achieve this output?
Event_date:20190512044638
Error_code:5858
Event_type:GPRS data
Duration:772
Missing_provider_id:46009
Event_date:20190512044638
Error_code:780678
Event_date:20190512064535
Error_code:5858
Event_type:GPRS data
Duration:2172
Missing_provider_id:722310
我希望这些数据采用以下输出格式:
i want this data to be in this output format:
Event_date Error_code Event_type Duration Missing_provider_id
20190512044638 5858 GPRS data 772 46009
20190512044638 780678
20190512064535 5858 GPRS data 2172 722310
推荐答案
此awk
可能会执行以下操作:(使用制表符分隔的字段)
This awk
may do: (tab separated fields)
如果缺少字段,所有步骤都必须按顺序进行,否则PS将失败.
PS this will fail if on field is missing, all need to come in order.
awk -F: 'NR==1 {print $1,$3,$5,$7,$9} {print $2,$4,$6,$8,$10}' RS= ORS='\n' OFS='\t' file
Event_date Error_code Event_type Duration Missing_provider_id
20190512044638 5858 GPRS data 772 46009
20190512044638 780678
20190512064535 5858 GPRS data 2172 722310
更通用的解决方案:
A more generic solution:
awk -F: 'NR==1 {print $1,$3,$5,$7,$9} {for(i=2;i<=NF;i+=2) printf "%s\t",$i;print ""}' RS= ORS='\n' OFS='\t' file
Event_date Error_code Event_type Duration Missing_provider_id
20190512044638 5858 GPRS data 772 46009
20190512044638 780678
20190512064535 5858 GPRS data 2172 722310
可以将
NR==1 {print $1,$3,$5,$7,$9}
设置为某些静态标头,例如NR==1 {print "F1","F2","F3","F4","F5"}
等
NR==1 {print $1,$3,$5,$7,$9}
can be set to some static header like NR==1 {print "F1","F2","F3","F4","F5"}
etc
这篇关于如何在unix中转置或旋转文本文件的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!