如何检测END之前的awk中的最后一行 [英] How to detect the last line in awk before END

查看:765
本文介绍了如何检测END之前的awk中的最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将最后一行添加到正在创建的文件中.如何在END之前检测awk中文件的最后一行?我需要这样做,因为变量在END块中不起作用, 所以我试图避免使用END.

I am trying to add last line to the file which I am creating. How is it possible to detect the last line of a file in awk before END ? I need to do this because the variables don't work in the END block, so I am trying to avoid using END.

awk ' { do some things..; add a new last line into file;}'

END之前,我不需要这个:

before END, I don't want this:

awk 'END{print "something new" >> "newfile.txt"}'

推荐答案

一种选择是使用getline函数来处理文件.成功时返回1,文件结束时返回0,错误时返回-1.

One option is to use getline function to process the file. It returns 1 on sucess, 0 on end of file and -1 on an error.

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

这篇关于如何检测END之前的awk中的最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆