runaway regular expression error in awk

I have a script which converts expressions in different units to standard units like: distance=1km -> distance=1000m.

This is my code:

#!/bin/bash
cat "$1" | grep '=' | awk -F= '{switch ($2) { case /^[0-9]+s$/ : print $1"="$2*1; break; case /^[0-9]+min$/ : print $1"="$2*60; break; case /^[0-9]+h$/ : print $1"="$2*3600; break; case /^[0-9]+d$/ : print $1"="$2*3600*24; break; case /^[0-9]+mm$/ : print $1"="$2/1000; break; case /^[0-9]+sm$/ : print $1"="$2/100; break; case /^[0-9]+dm$/ : print $1"="$2/10; break; case /^[0-9]+m$/ : print $1"="$2*1; break; case /^[0-9]+km$/ : print $1"="$2*1000; break; case /^[0-9]+mg$/ : print $1"="$2/1000000; break; case /^[0-9]+g$/ : print $1"="$2/1000; break; case /^[0-9]+kg$/ : print $1"="$2*1; break; case /^[0-9]+t$/ : print $1"="$2*1000; break; } }'
fi 

But when I'm trying to run it I have two errors:

awk: line 1: syntax error at or near {
awk: line 2: runaway regular expression / : print $ ...
2

1 Answer

I'm almost certain that the error is because your system is configured to use mawk (which currently does not appear to support the switch ... case construct) as the default implementation of awk - rather than gawk (GNU Awk):

$ sudo update-alternatives --set awk /usr/bin/mawk
update-alternatives: using /usr/bin/mawk to provide /usr/bin/awk (awk) in manual mode
$
$ echo 'abc:123' | awk -F: '{switch($2) {case /^[0-9]+$/: print $1; break;}}'
awk: line 1: syntax error at or near {
awk: line 1: runaway regular expression /: print $1 ...

whereas with GNU awk

$ sudo update-alternatives --set awk /usr/bin/gawk
update-alternatives: using /usr/bin/gawk to provide /usr/bin/awk (awk) in manual mode
$
$ echo 'abc:123' | awk -F: '{switch($2) {case /^[0-9]+$/: print $1; break;}}'
abc

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like