将分隔字段转换为具有名称和值的行
Transform delimited fields to lines with name and value
文件 a 包含字段名称:
timestamp,name,ip
文件 b 包含值:
2021-12-17 16:01:19.970,app1,10.0.0.0
2021-12-17 16:01:19.260,app1,10.0.0.1
当我使用awk时如下:
awk 'BEGIN{FS=",";OFS="\n"} {if(NR%3==0){print "----"};=;print;}' b
我得到:
----
2021-12-17 16:01:19.970
app1
10.0.0.0
----
2021-12-17 16:01:19.260
app1
10.0.0.1
有什么方法可以在每一行中合并 key:value?
我想要的输出是:
----
timestamp:2021-12-17 16:01:19.970
app:app1
ip:10.0.0.0
----
timestamp:2021-12-17 16:01:19.260
app:app1
ip:10.0.0.1
使用您展示的示例,请尝试执行以下 awk
程序。
awk '
BEGIN{ FS="," }
FNR==NR{
for(i=1;i<=NF;i++){
heading[i]=$i
}
next
}
{
print "----"
for(i=1;i<=NF;i++){
print heading[i]":"$i
}
}
' filea fileb
说明: 为以上添加详细说明。
awk ' ##Starting awk program from here.
BEGIN{ FS="," } ##Stating BEGIN section of this program and set FS to , here.
FNR==NR{ ##Checking condition which will be TRUE when filea is being read.
for(i=1;i<=NF;i++){ ##Traversing through all fields here.
heading[i]=$i ##Setting heading array index as i and value as current field.
}
next ##next will skip all further statements from here.
}
{
print "----" ##printing ---- here.
for(i=1;i<=NF;i++){ ##Traversing through all fields here.
print heading[i]":"$i ##Printing heading with index i and colon and value of current field.
}
}
' filea fileb ##Mentioning Input_file names here.
文件 a 包含字段名称:
timestamp,name,ip
文件 b 包含值:
2021-12-17 16:01:19.970,app1,10.0.0.0
2021-12-17 16:01:19.260,app1,10.0.0.1
当我使用awk时如下:
awk 'BEGIN{FS=",";OFS="\n"} {if(NR%3==0){print "----"};=;print;}' b
我得到:
----
2021-12-17 16:01:19.970
app1
10.0.0.0
----
2021-12-17 16:01:19.260
app1
10.0.0.1
有什么方法可以在每一行中合并 key:value? 我想要的输出是:
----
timestamp:2021-12-17 16:01:19.970
app:app1
ip:10.0.0.0
----
timestamp:2021-12-17 16:01:19.260
app:app1
ip:10.0.0.1
使用您展示的示例,请尝试执行以下 awk
程序。
awk '
BEGIN{ FS="," }
FNR==NR{
for(i=1;i<=NF;i++){
heading[i]=$i
}
next
}
{
print "----"
for(i=1;i<=NF;i++){
print heading[i]":"$i
}
}
' filea fileb
说明: 为以上添加详细说明。
awk ' ##Starting awk program from here.
BEGIN{ FS="," } ##Stating BEGIN section of this program and set FS to , here.
FNR==NR{ ##Checking condition which will be TRUE when filea is being read.
for(i=1;i<=NF;i++){ ##Traversing through all fields here.
heading[i]=$i ##Setting heading array index as i and value as current field.
}
next ##next will skip all further statements from here.
}
{
print "----" ##printing ---- here.
for(i=1;i<=NF;i++){ ##Traversing through all fields here.
print heading[i]":"$i ##Printing heading with index i and colon and value of current field.
}
}
' filea fileb ##Mentioning Input_file names here.