Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I have a shell script like the following -

find "." "Account" -maxdepth 1 -name "*.aspx" | xargs awk -f get_controls.awk

It passes multiple files to an awk script

BEGIN{
    FS="\""
}
...
/Src=/{
    printf("\t%s \r\n", $6);
}

I want to print out the current file name either from the shell script or from within awk at the start of the file.

Awk does know the current file name, it is in the FILENAME variable, but I can't determine the start of the file. I have tried (NR==1), but all the files are passed to awk as a stream and the value of NR keeps increasing.

Just figured it out as I type this. Will post answer below!

share|improve this question
add comment

2 Answers

up vote 1 down vote accepted

In addition to NR, which counts all records processed thus far, awk has an FNR variable, which counts the records in the current file.

To print the filename when you see the first line of a file:

awk 'FNR == 1 {print "now processing " FILENAME}' file ...

If you have access to gawk, you also get, in addition to BEGIN and END blocks, BEGINFILE and ENDFILE blocks.

share|improve this answer
    
thanks, did not know about FNR. –  bryan Sep 30 '11 at 20:16
add comment

Here is what I figured out while typing the question, sometimes I forget to think of awk as a programming language.

#! /usr/bin/awk -f
BEGIN{
    FS="\""
    OLDFILENAME=""
}


/Src=/{
    if(OLDFILENAME != FILENAME) 
    {
          printf("\r\n%s  \r\n", FILENAME);
          OLDFILENAME=FILENAME
        }
    printf("\t%s \r\n", $6);
}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.