Abhishek Chauhan
Abhishek Chauhan

Reputation: 309

How to convert a file with data in key = value format to a csv file in unix shell scripting?

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 a csv file like:

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

How can i do this in a shell script?

Upvotes: 3

Views: 629

Answers (1)

anubhava
anubhava

Reputation: 785246

You can use this 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 field separator as one of those characters in character class: [=(),]
  • -v OFS=, - Make output field separator as comma
  • NR==1 - Execute this block for first record only
  • 'NR==1{...} Will print all the headers of input file by printing fields 2, 4, 6...
  • {for (i=3; i<=NF; i+=2) ...} Will print all cells by printing fields 3, 5, 7...

Upvotes: 4

Related Questions