我接收的数值变量有时是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谢谢。
发布于 2011-08-19 12:43:38
在这方面,我也更喜欢sed:
echo 321 | sed -e 's/\([[:digit:]]\)/.\1/g' | cut -b2- -> 3.2.1
echo 32 | sed -e 's/\([[:digit:]]\)/.\1/g' | cut -b2- -> 3.2
或者没有剪裁,它看起来像这样
echo 321 | sed -e 's/\([[:digit:]]\)/.\1/g' -e 's/^\.//'发布于 2011-08-19 11:04:45
这是一个。这将适用于任何字符串长度。
#!/bin/bash
#s is the string
#fs is the final string
echo "Enter string"
read s
n="${#s}"
fs=""
i=0
for ((i=0; i<n; i++))
do
fs="$fs.${s:i:1}"
done
#find the length of the final string and
#remove the leading '.'
n="${#fs}"
fs="${fs:1}"
echo "$fs"发布于 2011-08-19 11:10:28
它没那么漂亮,但至少很短:
num=$(echo $S | sed -r "s/([0-9])/\1./g")
echo ${num%%.}https://stackoverflow.com/questions/7120518
复制相似问题