Add an index column to a csv using awk

Viewed 82

How can I add an index to a csv file using awk? For example lets assume I have a file

data.txt

col1,col2,col3
a1,b1,c1
a2,b2,c2
a3,b3,c3

I would like to add another column, which is the index. Basically I would like an output of

,col1,col2,col3
0,a1,b1,c1
1,a2,b2,c2
2,a3,b3,c3

I was trying to use awk '{for (i=1; i<=NF; i++) print $i}' but it does not seem to be working right. And what is the best way to just add a comma for the first line but add incrementing number and a comma to the rest of the lines?

4 Answers

You may use this awk solution:

awk '{print (NR == 1 ? "" : NR-2) "," $0}' file

,col1,col2,col3
0,a1,b1,c1
1,a2,b2,c2
2,a3,b3,c3

I would use GNU AWK for this task following way, let file.txt content be

col1,col2,col3
a1,b1,c1
a2,b2,c2
a3,b3,c3

then

awk 'BEGIN{OFS=","}{print NR==1?"":i++,$0}' file.txt

gives output

,col1,col2,col3
0,a1,b1,c1
1,a2,b2,c2
2,a3,b3,c3

Explanation: firstly I inform GNU AWK that output field separator (OFS) is ,, so arguments to print will be concatenated using that character. Then for each line I use so-called ternary operator i.e. condition?valueiftrue:valueiffalse to decide what will be 1st argument, for 1st line (NR==1) it is empty string for all else it is counter which will be first returned then increased by 1, 2nd argument to print is always whole original line ($0).

(tested in gawk 4.2.1)

gawk 'sub("^",substr(++_",",3^(NF~NR)))' FS='^$' \_=-2
mawk 'sub("^",++_+NF ? _",":",")' FS='^$' \_=-2 
,col1,col2,col3
0,a1,b1,c1
1,a2,b2,c2
2,a3,b3,c3
Related