Print line numbers starting at zero using awk
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)?
Solution 1:
NR starts at 1, so use
awk '{print NR-1 "," $0}'
Solution 2:
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
Solution 3:
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