awk

FNR-文件“记录数”

我们已经知道了NR是记录数(或者记录行号),打印所得到处理的文件的当前行号。

当我们给两个输入文件时NR将如何执行?NR保持多个文件之间越来越大。当body块开始处理第二个文件时,NR不会被重置为1,它会继续从先前文件最后的NR数值开始。

在下面的例子里,第1个文件有5条记录,第二个文件有5条记录。你可以看到,当body循环处理第二个文件时,NR从6开始(顶替1)。最终,在END块里,NR给出的是两个组合中的文件的记录总数。

$ awk 'BEGIN{FS=","}{print FILENAME": record number",NR,"is",$1;}END{print "Total number of records:",NR}' employee.txt employee-multiple-fs.txt
employee.txt: record number 1 is 101
employee.txt: record number 2 is 102
employee.txt: record number 3 is 103
employee.txt: record number 4 is 104
employee.txt: record number 5 is 105
employee-multiple-fs.txt: record number 6 is 101
employee-multiple-fs.txt: record number 7 is 102
employee-multiple-fs.txt: record number 8 is 103
employee-multiple-fs.txt: record number 9 is 104
employee-multiple-fs.txt: record number 10 is 105
Total number of records: 10

在上面的例子里,我们有两个输入文件(employee.txt 和employee-multiple-fs.txt)。每个文件有五条记录。因此,NR处理完第一个文件后继续增长。

FNR会给你当前文件中的记录数。因此,当awk完成执行第一个文件body块,并且开始下一个文件的body块时,FNR将重新从1开始。

$ awk 'BEGIN{FS=","}{print FILENAME ": record number",FNR,"is",$1;}END{print "Total number of records:",NR}' employee.txt employee-multiple-fs.txt
employee.txt: record number 1 is 101
employee.txt: record number 2 is 102
employee.txt: record number 3 is 103
employee.txt: record number 4 is 104
employee.txt: record number 5 is 105
employee-multiple-fs.txt: record number 1 is 101
employee-multiple-fs.txt: record number 2 is 102
employee-multiple-fs.txt: record number 3 is 103
employee-multiple-fs.txt: record number 4 is 104
employee-multiple-fs.txt: record number 5 is 105
Total number of records: 10

下面列子显示NR和FNR

$ cat fnr.awk
BEGIN {
    FS=","
    }
    {
    printf "FILENAME=%s NR=%s FNR=%s\n",FILENAME,NR,FNR;
    }
END {
    printf "END Block: NR=%s FNR=%s\n",NR,FNR
    }


$ awk -f fnr.awk employee.txt employee-multiple-fs.txt
FILENAME=employee.txt NR=1 FNR=1
FILENAME=employee.txt NR=2 FNR=2
FILENAME=employee.txt NR=3 FNR=3
FILENAME=employee.txt NR=4 FNR=4
FILENAME=employee.txt NR=5 FNR=5
FILENAME=employee-multiple-fs.txt NR=6 FNR=1
FILENAME=employee-multiple-fs.txt NR=7 FNR=2
FILENAME=employee-multiple-fs.txt NR=8 FNR=3
FILENAME=employee-multiple-fs.txt NR=9 FNR=4
FILENAME=employee-multiple-fs.txt NR=10 FNR=5
END Block: NR=10 FNR=5