shellunixawksedsh

How to add headers to a CSV file which already has some headers in it


My requirement it to add the new headers to an existing CSV file which already has some headers in the fist line. I need to add the new headers at the end of the existing headers. The value of the new headers will be empty; I just need to create the header.

For e.g. below is my CSV file

Cust_Name,Cust_ADD
A1,CBD
A2,CBE
A3,CBE

I need to add headers "salary,age" at the end of the CSV file.

I tried this code

sed -i "1s|\$|,$new_headers|" input.csv

It is giving me output like below

Cust_Name,Cust_ADD
,Salary,age
A1,CBD
A2,CBE
A3,CBE

The new headers are appearing on the second line.

Expected Output

Cust_Name,Cust_ADD,salary,age
A1,CBD,,
A2,CBE,,
A3,CBE,,

Solution

  • This might work for you (GNU sed):

    sed -i '1s/$/,salary,age/;1!s//,,/' file
    

    On the first line append ,salary,age.

    On all other lines append ,,

    N.B. The second substitute command because it is empty uses the previous regex but provides a new value to be appended i.e. s//,,/.