Add an index column to a csv using awk

Issue

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?

Solution

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

Answered By – anubhava

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published