65
votes

Can anyone tell me how to print line numbers including zero using awk?

Here is my input file stackfile2.txt

when I run the below awk command I get actual_output.txt

awk '{print NR,$0}' stackfile2.txt | tr " ", "," > actual_output.txt

whereas my expected output is file.txt

How do I print the line numbers starting with zero (0)?

4
Isn't it awk '{print NR-1,$0}'? - Anton Kovalenko
@user790049, don't make us chase links to find out what the problem is. Show a small sample input and tell us what you want the output to look like. stackoverflow.com/help/how-to-ask - glenn jackman
Sorry about that will take care from next time onwards - user790049
The links to the files are broken. Could you edit the question to include some proper minimal reproducible example? - fedorqui 'SO stop harming'

4 Answers

103
votes

NR starts at 1, so use

awk '{print NR-1 "," $0}'
14
votes

Using awk.

i starts at 0, i++ will increment the value of i, but return the original value that i held before being incremented.

awk '{print i++ "," $0}' file
8
votes

Another option besides awk is nl which allows for options -v for setting starting value and -n <lf,rf,rz> for left, right and right with leading zeros justified. You can also include -s for a field separator such as -s "," for comma separation between line numbers and your data.

In a Unix environment, this can be done as

cat <infile> | ...other stuff... | nl -v 0 -n rz

or simply

nl -v 0 -n rz <infile>

Example:

echo "Here 
are
some 
words" > words.txt

cat words.txt | nl -v 0 -n rz

Out:

000000      Here
000001      are
000002      some
000003      words
1
votes

If Perl is an option, you can try this:

perl -ne 'printf "%s,$_" , $.-1' file

$_ is the line
$. is the line number