Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print line numbers starting at zero using awk

Tags:

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

like image 777
user790049 Avatar asked Dec 23 '13 22:12

user790049


People also ask

What is awk '{ print $2 }'?

awk '{ print $2; }' prints the second field of each line. This field happens to be the process ID from the ps aux output. xargs kill -${2:-'TERM'} takes the process IDs from the selected sidekiq processes and feeds them as arguments to a kill command.

What is awk '{ print $1 }'?

If you notice awk 'print $1' prints first word of each line. If you use $3, it will print 3rd word of each line.


2 Answers

NR starts at 1, so use

awk '{print NR-1 "," $0}' 
like image 85
Lance Roberts Avatar answered Sep 27 '22 19:09

Lance Roberts


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 
like image 45
BMW Avatar answered Sep 27 '22 19:09

BMW