awk variable regexp works in AIX but not in SunOS?

Using awk variables for regular expressions is working for me in AIX. It is failing for me in SunOS. I don't know why. Can someone explain and/or suggest a fix for the SunOS version?

Here is a little test script. It runs fine in AIX:

$ cat test.ksh
#! /bin/ksh
print "Executed on OS: $( uname -rsv )" > test.out
( echo "line 1"; echo "middle line"; echo "last one" ) |
awk '
  BEGIN {
    re="iddl"
  }
  $0 ~ re {
    print "From awk: " $0
  }
' >> test.out 2>&1
$ ./test.ksh
$ cat test.out
Executed on OS: AIX 3 5
From awk: middle line

When I run the same script SunOS I get:

$ cat test.out
Executed on OS: SunOS 5.10 Generic_141414-07
awk: syntax error near line 5
awk: bailing out near line 5

Further, if I change $0 ~ re in the script to $0 ~ /iddl/, then it runs fine on SunOS (and of course AIX too). The problem is, I need a *variable* on the right hand side of the comparison, not a constant:

$ cat test_const.ksh
#! /bin/ksh
print "Executed on OS: $( uname -rsv )" > test_const.out
( echo "line 1"; echo "middle line"; echo "last one" ) |
awk '
  $0 ~ /iddl/ {
    print "From awk: " $0
  }
' >> test_const.out 2>&1
$ ./test_const.ksh
$ cat test_const.out
Executed on OS: SunOS 5.10 Generic_141414-07
From awk: middle line

Try using nawk or /usr/xpg4/bin/awk on Solaris.

BTW I get the same errors in SunOS (and success in AIX) if I try to use the match function
match($0,re) { ...

---------- Post updated at 04:50 PM ---------- Previous update was at 04:47 PM ----------

yeah, nawk works on both systems. Why not consistent behavior with awk?

Did you try both nawk and /usr/xpg4/bin/awk?

---------- Post updated at 03:55 PM ---------- Previous update was at 03:51 PM ----------

Because one of the main advantages of Solaris is it's backward compatibility. This is why sometimes outdated version of tools are in the default search path, but you always have choice to use nawk or xpg4 version if you need it's features.

/usr/xpg4/bin/awk works on Solaris but is not installed on my AIX system. So nawk gives me consistent behavior and is installed on both systems.

had some issues with this too...thanks for the advice

See this post for an explanation. AIX achieves backwards compatibility by other means and has the POSIX-compliant versions of commands under "/usr/bin" or "/bin", while Solaris has them under "/usr/xpg4/bin".

You might want to put something like:

case $OS in
     Solaris)
          PATH=$PATH:/usr/xpg4/bin
          ;;

     AIX)
          PATH=$PATH:/usr/bin
          ;;

esac

into the environment section of your scripts. I have a separate environment file for scripts which is full of such statements and declarations, which i source in (dot-run) at the beginning of all my scripts.

I hope this helps.

bakunin