How to convert data file in key = value format to csv file in unix shell scripts?

I have an input file of the format:

(key1=value1,key2=value2,key3=value3)
(key1=value4,key2=value5,key3=value6)

      

I want to convert this file to csv file, for example:

key1,key2,key3
value1,value2,value3
value4,value5,value6

      

How can I do this in a shell script?

+3


source to share


1 answer


You can use this one awk

to process this file:

awk -F'[=(),]' -v OFS=, 'NR==1{for (i=2; i<NF; i+=2) printf "%s%s", $i, (i<NF-2)?OFS:ORS}
              {for (i=3; i<=NF; i+=2) printf "%s%s", $i, (i<NF-2)?OFS:ORS}' input
key1,key2,key3
value1,value2,value3
value4,value5,value6

      



Explanation:

  • -F'[=(),]'

    - Make the field separator one of these characters in the character class: [=(),]

  • -v OFS=,

    - Make output field separator as comma
  • NR==1

    - execute this block for the first record only
  • 'NR==1{...}

    Will print all the headers of the input file by printing fields 2, 4, 6 ...
  • {for (i=3; i<=NF; i+=2) ...}

    Will print all cells by printing margins 3, 5, 7 ...
+4


source







All Articles