73

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)?

user790049
  • 1,154
  • 1
  • 9
  • 21

4 Answers4

121

NR starts at 1, so use

awk '{print NR-1 "," $0}'
jaypal singh
  • 74,723
  • 23
  • 102
  • 147
Lance Roberts
  • 22,383
  • 32
  • 112
  • 130
  • 6
    It might be nicer to set the output field separator to the comma: `awk -v OFS="," '{print NR-1, $0}' file`. – fedorqui Nov 27 '15 at 13:11
  • 1
    If you're looking for custom start value and other customizations, look at the answer based on `nl` below. – malana Feb 12 '19 at 14:52
18

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
BMW
  • 42,880
  • 12
  • 99
  • 116
12

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
Jon
  • 2,373
  • 1
  • 26
  • 34
2

If Perl is an option, you can try this:

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

$_ is the line
$. is the line number

Chris Koknat
  • 3,305
  • 2
  • 29
  • 30