如何使用awk检测嵌入的字段名称并重新排序字段? [英] How do I detect embbeded field names and reorder fields using awk?
本文介绍了如何使用awk检测嵌入的字段名称并重新排序字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下数据:
"b":1.14105,"a":1.14106,"x":48,"t":1594771200000
"a":1.141,"b":1.14099,"x":48,"t":1594771206000
...
我试图以给定的顺序显示数据,并且仅显示三个字段.由于不能保证字段顺序,因此我需要阅读"tag"标签.每行的每个逗号分隔列.
I am trying to display data in a given order and only for three fields. As the fields order is not guaranteed, I need to read the "tag" for each comma separated column for each line.
我尝试使用awk
解决此任务:
I have tried to solve this task using awk
:
awk -F',' '
{
for(i=1; i<=$NF; i++) {
if(index($i,"\"a\":")!=0) a=$i;
if(index($i,"\"b\":")!=0) b=$i;
if(index($i,"\"t\":")!=0) t=$i;
}
printf("%s,%s,%s\n",a,b,t);
}
'
但是我得到了
,,
,,
...
在上述数据示例中,我期望:
In the above data sample, I would expect:
"a":1.14106,"b":1.14105,"t":1594771200000
"a":1.141,"b":1.14099,"t":1594771206000
...
注意:我正在使用FreeBSD随附的awk
Note: I am using the awk shipped with FreeBSD
推荐答案
带有awk
和一个数组:
awk -F '[:,]' '{for(i=1; i<=NF; i=i+2){a[$i]=$(i+1)}; print "\"a\":" a["\"a\""] ",\"b\":" a["\"b\""] ",\"t\":" a["\"t\""]}' file
或
awk -F '[":,]' '{for(i=2; i<=NF; i=i+4){a[$i]=$(i+2)}; print "\"a\":" a["a"] ",\"b\":" a["b"] ",\"t\":" a["t"]}' file
输出:
"a":1.14106,"b":1.14105,"t":1594771200000
"a":1.141,"b":1.14099,"t":1594771206000
这篇关于如何使用awk检测嵌入的字段名称并重新排序字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文