Doubt in awk programing

i wrote an awk progarm to calculate throughput from a ns2 trace file. i want this program to act on multiple trace files and it should display each output in a single output file can anyone please clear my doubt i tried with

awk -f awkscript inputfile1 inputfile2>outputfile
but it calculates the sum of all the throughputs and displaying

How about using a for loop?

for file in inputfile[1-2]
do
   awk -f awkscript "$file" >> outputfile
done

Or here is another example:

awk ' BEGIN {
        F = FILENAME
} F == FILENAME  {
        t += $0
} F != FILENAME {
        print t >> "outputfile"
        t = 0
        t += $0
} {
        F = FILENAME
} END {
        print t >> "outputfile"
} ' inputfile1 inputfile2
1 Like

@bipinajith: In the first example instead of >> file you could use done > file instead, then you do not need to append...
regarding the awk, FILENAME is not initialized in the BEGIN section and also there you do not need to append from within awk, but you can redirect stdout to a file.. You could also let FNR==1 mark the beginning of a new file.

That is what I thought, but can you explain this?

$ awk ' BEGIN {
>         F = FILENAME
>         print F
> } ' inputfile1 inputfile2
inputfile1

I just tried it with gawk, mawk and bwk, and I got:

$ awk ' BEGIN { F = FILENAME ; print F }' inputfile1 inputfile2

$

What version of awk are you using?

You are correct about gawk .

But I tested this code in below awk version (OS: HP-UX)

$ what /usr/bin/awk
/usr/bin/awk:
        $Revision: 92453-07 linker linker crt0.o B.11.16.01 030415 $
         main.c $Date: 2008/05/19 14:40:42 $Revision: r11.23/3 PATCH_11.23 (PHCO_38267)
         lib.c $Date: 2007/02/23 16:15:06 $Revision: r11.23/2 PATCH_11.23 (PHCO_36053)
         run.c $Date: 2008/05/19 14:40:53 $Revision: r11.23/1 PATCH_11.23 (PHCO_38267)
         $Revision: @(#) awk R11.23_BL2008_0602_1 PATCH_11.23 PHCO_38267

And I do get the FILENAME printed in BEGIN block.

Beside gawk, mawk and bwk, it also does not work with /usr/xpg4/bin/awk. So it may work on HPUX, but it should not be relied upon.. According to the POSIX specification:

awk: Variables and Special Variables

Understood. In fact that is what I thought, it is my bad that I posted that code even though it works in HP-UX. Sorry about that.

---------- Post updated at 14:52 ---------- Previous update was at 14:41 ----------

I searched the internet and found that this is a bug in HP-UX awk!!

HP-UX awk gets it wrong and fills FILENAME with the first command line argument.

Here is an example:

$ awk ' BEGIN { print FILENAME } ' f=10 inputfile1
f=10

You can find some discussions regarding this bug here