开发者

Shell variable interpreted wrongly in awk

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"
      开发者_C百科}
     }
    ' dummy

dummy is file with single blank line.

Thanks,


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.


This is not a bug, but an error in your code. The problematic line is:

if (  ismodel != foo ) {

Here foo should be "foo". Right now you are comparing with an empty variable. This gives false when you have a match, and true when you have no match. So the problem is not the way you use the shell variables.

But as the other answerers have said, the preferred way of passing arguments to awk is by using the -v switch. This will also work when you decide to put your awk script in a separate file and prevents all kind of quoting issues.

I'm also not sure about your usage of a dummy file. Is this just for the example? Otherwise you should omit the file and put all your code in the BEGIN {} block.


use -v option to pass in variable from the shell

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜