使用"awk"在“开始"部分中打印文件中的行数 [英] Using `awk` to print number of lines in file in the BEGIN section

查看:535
本文介绍了使用"awk"在“开始"部分中打印文件中的行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写awk脚本,在完成任何操作之前,请告诉用户文件中有多少行.我在END部分中知道如何执行此操作,但在BEGIN部分中却无法执行此操作.我已经搜索了SE和Google,但在END部分或bash脚本的一部分中只找到了六种方法来进行此操作,而不是在进行任何处理之前未怎么做.我希望有以下类似的东西:

I am trying to write an awk script and before anything is done tell the user how many lines are in the file. I know how to do this in the END section but unable to do so in the BEGIN section. I have searched SE and Google but have only found a half dozen ways to do this in the END section or as part of a bash script, not how to do it before any processing has taken place at all. I was hoping for something like the following:

#!/usr/bin/awk -f

BEGIN{
        print "There are a total of " **TOTAL LINES** " lines in this file.\n"
     }
{

        if($0==4587){print "Found record on line number "NR; exit 0;}
}

但是,即使有可能,也无法确定如何执行此操作.谢谢.

But have been unable to determine how to do this, if it is even possible. Thanks.

推荐答案

您可以读取文件两次.

awk 'NR!=1 && FNR==1 {print NR-1} <some more code here>' file{,}

在您的示例中:

awk 'NR!=1 && FNR==1 {print "There are a total of "NR-1" lines in this file.\n"} $0==4587 {print "Found record on line number "NR; exit 0;}' file{,}

您可以使用file file代替file{,}(它只会显示两次).
NR!=1 && FNR==1仅在第二个文件的第一行是正确的.

You can use file file instead of file{,} (its just make it show up twice.)
NR!=1 && FNR==1 this will be true only at first line of second file.

要使用awk脚本

#!/usr/bin/awk -f
NR!=1 && FNR==1 {
    print "There are a total of "NR-1" lines in this file.\n"
    } 
$0==4587 {
    print "Found record on line number "NR; exit 0
    }

awk -f myscript file{,}

这篇关于使用"awk"在“开始"部分中打印文件中的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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