awk : Not able to access the passed parameter

2019-08-12 16:19发布

问题:

I am invoking myAwk.awk like below from shell script,

awk -f myAwk.awk -v inputKeyword="SEARCH" file2.xml

$bash: cat myAwk.awk
BEGIN{
print "This is from awk script:"  inputKeyword; //This prints SEARCH string. Fine.
}

/<record / { i=1 }
i { a[i++]=$0 }
/<\/record>/ {
    if (found) {
        for (i=1; i<=length(a); ++i) print a[i] >> resultFile.xml
    }
    i=0;
    found=0
}
/<keyword>inputKeyword<\/keyword>/ { found=1 }  //Looks like the value for inputKeyword is not available here.
//There are no errors though.

How can I make the value of inputKeyword to be available at my required place?

回答1:

You need to change the line,

/<keyword>inputKeyword<\/keyword>/ { found=1 }

to

$0 ~ "<keyword>"inputKeyword"</keyword>" { found=1 }

You do not required //, if matching pattern(regex) is in variable. awk won't interpolate what's between //. It will be considered just a string in there.



回答2:

According to the man page you should pass the options before -f:

SYNOPSIS

   `gawk [ POSIX or GNU style options ] -f program-file [ -- ] file ...`
   `gawk [ POSIX or GNU style options ] [ -- ] program-text file ...`