Adding a column to a file

Hello all,

I need to add a coloumn at the 5th Position of a file, Can this be done using awk or sed.

Sample Input

1008,300186,R,2009,0,2,2,3,2,0,1,1,1,1,2,1,1,0,2,1,1,0,2,2,2,2,0,0,0,0,1,0,2,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,,0,0,0,0,0,0,0,0,3,2,3,1,1,1,

Ouput:

1008,300186,R,2009,,0,2,2,3,2,0,1,1,1,1,2,1,1,0,2,1,1,0,2,2,2,2,0,0,0,0,1,0,2,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,,0,0,0,0,0,0,0,0,3,2,3,1,1,1,
awk -F, -vOFS=, '{$4=$4 OFS}1'

Will simply add that comma into 4th field.

1 Like

Thanks it worked , It would be really kind if you could explain what the code does a bit elaborately.

Make sure there are no empty lines otherwise they will be replaced by 4 commas. You could exclude that by testing for the number of fields.. ( NF{ $4 .. )

Is the second line part of the first line? If not, does it not need to get changed too?

sed alternative:

sed 's/,/,,/4' infile

Yes the second line is a part of the first line