File a is containing field names:
timestamp,name,ip
File b contains values:
2021-12-17 16:01:19.970,app1,10.0.0.0
2021-12-17 16:01:19.260,app1,10.0.0.1
When I use awk as follows:
awk 'BEGIN{FS=",";OFS="\n"} {if(NR%3==0){print "----"};$1=$1;print;}' b
I get:
----
2021-12-17 16:01:19.970
app1
10.0.0.0
----
2021-12-17 16:01:19.260
app1
10.0.0.1
Any way to merge key:value in each line? The output I want is:
----
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
CodePudding user response:
With your shown samples, please try following awk
program.
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
Explanation: Adding detailed explanation for above.
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.