从变量开始处修剪某个字符

问题描述 投票:0回答:1

我想从变量的开头开始将字符零“ 0”修剪掉。在以下功能中,输入是IP地址的一部分,其值介于0到255之间。

1),当值是1位数字(0-9)结束时,输入也是1位数字(0-9),那么如果它是2位数字(00-09)或3位数字( 000-009)从一开始就修剪1或2个零“ 0”,以便输出为(0-9)。

2)当值是2位数字(10-99)结束时,输入也是2位数字(10-99),则如果它是3位数字(010-099)修剪零“ 0”,则不要修剪任何内容从一开始就输出(10-99)。

3)当值是3位数字(100-255)时,请勿修剪任何内容。

function SubnetIP () {
while true; do
echo -e '\n\n\e[1;33mInput the IP Number that your Subnet want to start\e[0m\n'
echo -e '\n\e[32mInput only the third (3) section of the IP Range that you want .
(e.g. For Subnet 192.168.224.0 Input 224\e[0m\n'
echo -e '\e[38;5;208mInput a number between 0 and 255\e[0m'
echo -en '\e[95mSubnet IP : \e[0m' ; read -n3 ips ; echo
    [[ $ips =~ ^[0-9]+$ ]] || { echo -e '\n\e[38;5;208mSorry input a number between 0 and 255\e[0m\n' ; continue; }
    if ((ips >= 0 && ips <= 255)); then break ; else echo -e '\n\e[31mNumber out of Range, input a number between 0 and 255\e[0m\n' ; fi

done
echo -e '\n\nIP : '${ips}'\n\n'
}
bash function variables sh trim
1个回答
0
投票

您已经确定只接受数字0-9,所以很好。将经过验证的输入值传递到“ expr”以去除前导零:

[[ $ips =~ ^[0-9]+$ ]] || { echo -e '\nSorry input a number ' ... etc.}
ips=$(expr ${ips})
if ((ips >= 0 && ips <= 255)); then break ; else echo -e ... etc.
© www.soinside.com 2019 - 2024. All rights reserved.