switch/case doesn't work in awk

awk, linux

Solution

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.

Problem

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!

Original source