awk variable assignment in a file

Hi All,

I have a little awk script which uses a variable (x):

awk -v x=0 'NF != 6 { ++x } END { print "This batch had " x " errors out of ", NR" records"}'

But when I've tried to put the command in a file I can't seem to declare the variable. I've managed to simplify the code so that I don't use the variable but this changes the output. I'm doing this because I'm converting it to perl with a2p. I've just converted the output perl ( my $X; $X = 0; ) so that my output is correct but I've really like to know how to declare awk variables in files. Can any one help?

My simplified code looks like this:

NF != 6 { x++ }
END { print "This batch had " x " errors out of ", NR" records"}

Many thanks,
:slight_smile:

I don't really understand your question but maybe this is what you are looking for:

eval $(awk -v x=0 'NF != 6 {++x} END {print "ERROR_CNT="x";RECORD_CNT="NR}' yourdata)
echo "$ERROR_CNT of $RECORD_CNT had errors"

This turns your print statement into variable assignments that can be used in the shell.

2 of 4 had errors

Hi tmarikle,

Thanks for your response. I don't think I described the problem very clearly; let me try again: I can run my command as it is on the command line and it works fine but if I want to run it from a file:

awk -f awk3 mydata

Where awk3 is my command file - how do I declare the variable within the file (awk3)?

I can do this:

awk -f -v x=0 awk3 mydata

But to get an exact perl output from a2p I need to define the variable 'x' in awk3 - this is where I have a problem... This is a stumbling block for me when it comes to writing multi-line awk scripts anyway so I'd like to overcome it.

Hope this is a little clearer.

Many thanks,

:slight_smile:

Maybe I'm still unclear but here's another attempt. Awk variables are defined upon first use, however, you can explicitly define variables throughout the script but awk provides an initialization procedure called BEGIN.

awk '
    BEGIN { x=0 }
    NF != 6 { ++x}
    END { print "This batch had " x " errors out of ", NR" records" }' yourdata

Is that more what you're looking for?

Hi tmarikle,

That's what I needed! Thanks!

If I place what's between the quotes in a file I can then run the command:

awk -f awk5 mydata

Which means that

  1. I now know how to declare variables in a file.
  2. I can now use it to create my perl using: a2p awk5

Cheers,

:smiley: