Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

switch/case doesn't work in awk

Tags:

linux

awk

I am writing a simple awk in redhat linux,but found switch/case doesn't work for me. I searched on web, but didn't find a solution. The following is my code:

 BEGIN {
   foo = 1;
     switch (foo) {
         case 3:
         print "x";
         break;
         case 2:
         print "y" ;
         break;
         case 1:
         print "z" ;
         break;
         default:
         print "default" ;
      }
 }

the awk I am running is GNU Awk 3.1.5. I got the following err:

awk -f test.awk

awk: test.awk:3:      switch (foo) {
awk: test.awk:3:                   ^ syntax error
awk: test.awk:5:          case 3:
awk: test.awk:5:                ^ syntax error
awk: test.awk:8:          case 2:
awk: test.awk:8:                ^ syntax error
awk: test.awk:11:          case 1:
awk: test.awk:11:                ^ syntax error
awk: test.awk:14:          default:
awk: test.awk:14:                 ^ syntax error

can anybody please help me out? thank you!

like image 771
Gary Avatar asked Jul 09 '12 19:07

Gary


1 Answers

The GAWK manual says:

6.4.5 The switch Statement

NOTE: This subsection describes an experimental feature added in gawk 3.1.3. It is not enabled by default. To enable it, use the ‘--enable-switch’ option to configure when gawk is being configured and built. See Section B.2.2 [Additional Configuration Options], page 269, for more information.

The switch statement allows the evaluation of an expression and the execution of statements based on a case match. Case statements are checked for a match in the order they are defined. If no suitable case is found, the default section is executed, if supplied.

Which version of gawk are you using? Was it compiled with the --enable-switch option?

If you can't tell whether gawk was compiled with --enable-switch and you are getting syntax errors, it is reasonable to infer that it is not. I'm using gawk 3.1.8 compiled with the default configuration and get pretty much exactly the errors you are seeing on your script. Given that, it is highly unlikely that your version is compiled with the necessary configuration option. It isn't hard to recompile gawk with the option if you want to.

like image 144
Jonathan Leffler Avatar answered Oct 11 '22 05:10

Jonathan Leffler