Usage of a variable in awk BEGIN

Hi,

diffcount=`awk 'BEGIN { while ( getline < "/scripts/matt/text.server1.reference" ) { arr[$0]++ } } { if (!( $0 in arr ) ) { print } }' $TMPDIR/$(basename $0 .sh) | wc -l`
        if [[ $diffcount -eq 0 ]]; then
        OK="OK - No change in the interfaces status"
        elif [[ $diffcount -gt 0 ]]; then
        DIFF=`awk 'BEGIN { while ( getline < "/scripts/matt/text.server1.reference" ) { arr[$0]++ } } { if (!( $0 in arr ) ) { print } }' $TMPDIR/$(basename $0 .sh).$1 | awk -F "|" '{print$2,"("$3")"}' ORS=' ' |  awk '{for(i=1;i<NF;i++)if(i%2==0){$i=$i","} }1'

i have a part of a script where i can output the difference between two text files. If there is a difference it will output it in the same line, comma separated. All works well, apart that i cannot understand how a variable can be entered to represent the file path "/scripts/matt/ and the name of the file as $1 in script, where $1 = server1" as when i do that it fails. Note that after the getline function, the other file (in which text.server1.reference is being compared with) "$TMPDIR/$(basename $0 .sh)" works fine when pushed to a variable. So this should be something like:

diffcount=`awk 'BEGIN { while ( getline < "/$MATTDIR/text.$1.reference" ) { arr[$0]++ } } { if (!( $0 in arr ) ) { print } }' $TMPDIR/$(basename $0 .sh) | wc -l`

Can you insert variables in the getline part?

Rgds,

Matt

Pass parameters into awk with the -v option:

awk -vMDIR="$MATTDIR" ' ... "/scripts/" MDIR "..."

And, yes, you can getline var < file (c.f. man awk )
And, how about saving one execution of your first awk script like

diffcnt=$(awk '...' file | tee /tmp/WRK | wc -l)

and then work from the WRK file?

1 Like

Hi,

Thanks for that hint. i have tried to push the following variables into the -v, so command looks like this:

HOMEDIR=/matt/scripts

awk -v MDIR="$HOMEDIR/text.$1.reference" 'BEGIN { while ( getline < "MDIR" ) { arr[$0]++ } } { if (!( $0 in arr ) ) { print } }' $TMPDIR/$(basename $0 .sh).$1 | awk -F "|" '{print$2,"("$3")"}' ORS=' ' |  awk '{for(i=1;i<NF;i++)if(i%2==0){$i=$i","} }1

Note the $1 is the first argument given to the script (the hostname for example)

it takes a while, meaning that it fails. Running it with a verbose mode, i could see that variable assignment MDIR is taken into account as it displays the whole path including the $1 variable, however it seems i'm doing something wrong in the getline < "MDIR". I tried also removing the "<"

Rgds,

Matthew

You should not quote the variable MDIR within awk code, because then it will be regarded as the string "MDIR" .

Also it is best to use: while((getline ...)>0) , seeing as getline returns 1 for a successful input, 0 for end of file, and -1 for an error...

1 Like

Why don't you consider combining those three awk s into one?