我有一个脚本,可以将不同单位的表达式转换为标准单位,例如:distance=1km -> distance=1000m。
这是我的代码:
#!/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
但是当我尝试运行它时出现两个错误:
awk: line 1: syntax error at or near {
awk: line 2: runaway regular expression / : print $ ...
答案1
我几乎可以肯定,错误是因为您的系统配置为使用mawk
(当前似乎不支持构造switch ... case
)作为默认实现awk
- 而不是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 ...
而使用 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