Print line numbers starting at zero using awk

匿名 (未验证) 提交于 2019-12-03 02:45:02

问题:

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

回答1:

NR starts at 1, so use

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


回答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 


回答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 


回答4:

If Perl is an option, you can try this:

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

$_ is the line
$. is the line number



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!