Shell variable misinterpreted in awk

In the following code, I am trying to pass shell varibale to awk. But when I try to run it as a.sh foo_bar, the output is: "foo is not declared", and when I run it as bar.b.sh, the output is "foo declared". Is there an error in awk or am I doing something wrong here?

I am using gawk-3.0.3.

#!/bin/awk

model=$1

awk ' {

      match("'$model'", /foo/)
      ismodel=substr("'$model'", RSTART, RLENGTH)
      if (  ismodel != foo ) {
        print  " foo is not declared"
      } else {
        print  " foo is declared"
      }
     }
    ' dummy

dummy is a file with a single empty line.

Thank,

+3
source share
3 answers

This is not an error, but an error in the code. Problem line:

if (  ismodel != foo ) {

foo "foo". . false, , true, . , , .

, , awk -v. , awk script .

. ? BEGIN {}.

+1

AWK :

awk -v awkvar=$shellvar 'BEGIN {print awkvar}'

script script, AWK shebang line. #!/bin/sh.

+2

-v

awk -v model="$1" '{
  match(model, /foo/)
   .....
}
' dummy
0

Source: https://habr.com/ru/post/1760687/


All Articles