Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell variable interpreted wrongly in awk

Tags:

awk

gawk

In 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 printed is "foo is not declared" and when I run it as a.sh bar_bar the output printed is " foo is declared" . Is there a bug in awk or I am 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 file with single blank line.

Thanks,

like image 796
Anil Rana Avatar asked Feb 13 '26 23:02

Anil Rana


1 Answers

You should use AWK's variable passing instead of complex quoting:

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

Your script is written as a shell script, but you have an AWK shebang line. You could change that to #!/bin/sh.

like image 193
Dennis Williamson Avatar answered Feb 15 '26 14:02

Dennis Williamson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!