0

I've got a csv file with this content:

col1, col2, col5
1,    1,    1
2,    2,    2
3,    3,    3
4,    4,    4

I need to add a column in the third position of the file with a header but with empty values.

col1, col2, col3, col4
1,    1,        ,   1
2,    2,        ,   2
3,    3,        ,   3
4,    4,        ,   4

Is there any way to do it using one of the Linux commands like cat, sed, awk or cut?

I know that with cut is possible to modify a file by columns cut -d , -f1,2,3 file1 > file2. But it seems does not have the option to add a custom column.

Any help would be much appreciated.

2
  • What are the spaces after ,s in the file?
    – nitishch
    Aug 5, 2016 at 11:24
  • Do you mean the spaces in col3? those are empty values. The file is delimited by commas. Aug 5, 2016 at 11:29

2 Answers 2

2

Following is the sed command to achieve the result:

sed '1s/\(.*,\)\([^,]*\)$/\1col3,\2/;
     2,$s/\(.*,\)\([^,]*\)$/\1,\2/' file.csv

This finds the last , in a line and replaces it with

  • col3, on first line
  • , on all other lines

This command just prints the required output to stdout. If you want to edit the file in place, give -i switch to the above command.

1
$ awk 'BEGIN { FS=","; OFS=",\t" };
       FNR == 1 { print $1,$2,"col3","col4" };
       FNR  > 1 { print $1,$2,"\t",$3 }' file.csv 
col1,    col2,  col3,   col4
1,      1,      ,       1
2,      2,      ,       2
3,      3,      ,       3
4,      4,      ,       4

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .