开发者

Setting FNR value in awk

Is there any way you can alter the default value of FNR and then output it to the screen.

I have tried:

(piped output....) | awk '{FNR=0} {print $0, FNR}'

I am hoping that solution will be interha开发者_开发知识库ngeable with NR.


Yes, by using BEGIN:

$ awk 'BEGIN {FNR=2} {print $0, FNR}' file.txt
one 3
two 4
three 5
four 6

However, this seems not to work when input is not stdin (i.e. a file argument is given; at least not in GNU awk).


Why not declare your own offset variable:

(piped output....) |  awk 'BEGIN {offset=2} {print $0, FNR+offset}'


The correct answer is: DO NOT DO THAT!!!! Leave FNR alone, it is what it is. If you need some counter that represents something other than the number of records read so far in the current file, then simply create a counter to represent that, don't go messing with the meaning of the built-in variables.


$ awk 'FNR > 2 {print $0, FNR}' yourfilename

FNR isn't necessarily interchangeable with NR. If you specify multiple files, FNR reinitializes to zero before each file. NR doesn't.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜