How to convert data file in key = value format to csv file in unix shell scripts?
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 to share