我正在尝试将最后一行添加到我正在创建的文件中.如何在awk之前检测文件的最后一行END?我需要这样做,因为变量在END块中不起作用,所以我试图避免使用END.
awk ' { do some things..; add a new last line into file;}'
以前END,我不想要这个:
awk 'END{print "something new" >> "newfile.txt"}'
Bir*_*rei 10
一种选择是使用getline函数来处理文件.它1在成功,0文件结束和-1错误时返回.
awk '
    FNR == 1 {
        ## Process first line.
        print FNR ": " $0;
        while ( getline == 1 ) {
            ## Process from second to last line.
            print FNR ": " $0;
        }
        ## Here all lines have been processed.
        print "After last line";
    }
' infile
假设infile有这样的数据:
one
two
three
four
five
输出将是:
1: one                                                                                                                                                                                                                                       
2: two                                                                                                                                                                                                                                       
3: three
4: four
5: five
After last line
您可以使用ENDFILE,它在之前执行END:
$ awk 'END {print "end"} ENDFILE{print "last line"}'  /dev/null /dev/null
last line
last line
end
ENDFILE 存在于最新版本的 awk(我认为 >4.0)中。
$ cat file 
1
2
3
4
5
通过两次读取同一文件(推荐)
$ awk 'FNR==NR{last++;next}{print $0, ((last==FNR)?"I am Last":"")}' file file
1
2
3
4
5 I am Last
运用 getline
$ awk 'BEGIN{while((getline t < ARGV[1]) > 0)last++;close(ARGV[1])}{print $0, ((last==FNR)?"I am Last":"")}' file
1
2
3
4
5 I am Last
打印上一行。当前行为2时,打印行1,当前行为3时,打印行2。
awk '{
    if (NR>1) {
        # process str
        print str;
    }
    str=$0;
}
END {
    # process whatever needed before printing the last line and then print the last line.
    print str;
}'