Shell – How to Add Headers to a CSV File with Existing Headers Using Unix, AWK, SED, and SH

awksedshshellunix

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,,

Best Answer

With any awk

% awk '{NR == 1 ? $0=$0",salary,age" : $0=$0",,"}1' file.csv
Cust_Name,Cust_ADD,salary,age
A1,CBD,,
A2,CBE,,
A3,CBE,,

Data

% cat file.csv
Cust_Name,Cust_ADD
A1,CBD
A2,CBE
A3,CBE