Linux – Output a CSV file from the shell

Output a CSV file from the shell… here is a solution to the problem.

Output a CSV file from the shell

Hello, I have an input file in this format.

[Header A]
key1 value1
key2 value2

[Header B]
header1    header2    header3   // separated by tab
1            2          3     //separated by tab
a            b          c     //separated by tab

[Header C]
a
b
c

I have to output anything in HeaderB as another csv file
So the CSV file looks like

header1,header2,header3
1,2,3
a,b,c

I wrote a python script to do this, but asked it to be done via shell commands. I don’t know much about writing complex shell commands. Can anyone help me.

Thanks

Solution

This works for you :

awk -F'\t' '/\[Header B\]/{f=1; next} /^$/{f=0} f{gsub(/\t/,","); print}' file

Example

$ awk -F'\t' '/\[Header B\]/{f=1; next} /^$/{f=0} f{gsub(/\t/,","); print}' file
header1,header2,header3
1,2,3
a,b,c

Related Problems and Solutions