Home > Enterprise >  Add an index column to a csv using awk
Add an index column to a csv using awk

Time:07-07

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?

CodePudding user response:

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

CodePudding user response:

Use this Perl one-liner:

perl -pe '$_ = ( $. > 1 ? ($. - 2) : "" ) . ",$_";' data.txt > out.txt

The Perl one-liner uses these command line flags:
-e : Tells Perl to look for code in-line, instead of in a file.
-p : Loop over the input one line at a time, assigning it to $_ by default. Add print $_ after each loop iteration.

$. : Current input line number.

SEE ALSO:
perldoc perlrun: how to execute the Perl interpreter: command line switches
perldoc perlvar: Perl predefined variables

CodePudding user response:

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