Print line numbers starting at zero using awk

Awk

Awk Problem Overview


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

Awk Solutions


Solution 1 - Awk

NR starts at 1, so use

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

Solution 2 - Awk

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 - Awk

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

Solution 4 - Awk

If Perl is an option, you can try this:

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

$_ is the line
$. is the line number

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser790049View Question on Stackoverflow
Solution 1 - AwkLance RobertsView Answer on Stackoverflow
Solution 2 - AwkBMWView Answer on Stackoverflow
Solution 3 - AwkJonView Answer on Stackoverflow
Solution 4 - AwkChris KoknatView Answer on Stackoverflow