Search code examples
textawktext-processing

Using `awk` to print number of lines in file in the BEGIN section


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.


Solution

  • You can read the file twice:

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

    In your example:

    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{,}
    

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


    To use an awk script containing:

    #!/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
        }
    

    call:

    awk -f myscript file{,}