Sams
Sams

Reputation: 17

Extraneous output in awk

I'm parsing a file using awk.

BEGIN{FS=":"; PPH = 0; NAME=""}

    NAME=$1;
    PPH=$2;
    PAY=PPH*HOURS;
    {print NAME " " PAY}

END{print "end" }

This is the basic structure of the program. I'm running it as

 awk -f file.awk inputfile.dat

The issue I'm having is that it prints each line six times and then what it should print for the print NAME and PAY line. I'm kind of confused why this is happening as I only have the two print lines and it seems to be unrelated to the number of lines in the input file.

Upvotes: 0

Views: 29

Answers (1)

jas
jas

Reputation: 10865

The problem is that the assignment statements need to be part of the action, that is, they need to be inside the second set of curly braces.

BEGIN {FS=":"; PPH = 0; NAME=""}

{
    NAME=$1;
    PPH=$2;
    PAY=PPH*HOURS;
    print NAME " " PAY
}

END {print "end" }

Remember that everything in awk is a pattern followed by an action within curly braces. If the action is omitted, the default action is to print the line. Since the assignments were not in curly braces they were being interpreted as patterns, evaluating to true, causing the line to be printed multiple times.

Upvotes: 2

Related Questions