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?
Advertisement
Answer
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