【发布时间】:2011-10-30 12:50:50
【问题描述】:
我收到的数字变量有时是 2,有时是 3 位,例如“321”和“32”。我想在每个数字之间加上一个点。因此,如果我收到“32”,我必须回显“3.2”,如果收到“321”,我就回显“3.2.1”。
这就是我所做的:
S='321'
SL="${#S}" #string lentgh
n1=`echo $S | cut -c 1-1`
n2=`echo $S | cut -c 2-2`
if [ "$SL" -eq 2 ]; then
echo $n1.$n2
elif [ "$SL" -eq 3 ]; then
n3=`echo $S | cut -c 3-3`
echo $n1.$n2.$n3
else
die 'Works only with 2 or 3 digits'
fi
我的问题是:有没有更短的方法来做同样的事情?
更新: 更短但仍然冗长:
SL="${#1}" #string lentgh
S=$1
if [ "$1" -eq 3 ]; then
$n3=".${S:2:1}"
fi
if [ "$SL" -lt 2 ] && [ "$SL" -gt 3 ]; then
die 'Works only with 2 or 3 digits'
fi
echo "${S:0:1}.${S:1:1}$n3"
更新 1:
如果我包含 if 块,sed+regex 版本将与纯 bash 版本一样长:
SL="${#1}" #string lentgh
S=$1
N=$(echo $S | sed -r "s/([0-9])/\1./g")
echo ${N%%.}
if [ "$SL" -lt 2 ] && [ "$SL" -gt 3 ]; then
die 'Works only with 2 or 3 digits'
fi
或者,使用带有两个表达式的单行 sed+regex:
SL="${#1}" #string lentgh
echo $1 | sed -e 's/\([[:digit:]]\)/.\1/g' -e 's/^\.//'
if [ "$SL" -lt 2 ] && [ "$SL" -gt 3 ]; then
die 'Works only with 2 or 3 digits'
fi
谢谢。
【问题讨论】: