Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Transform delimited fields to lines with name and value

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading