简体   繁体   English

从变量的开头修剪某个字符

[英]Trim a certain character from the begin of a variable

I want to trim from the beginning of a variable the characters zero "0".我想从变量的开头修剪字符零“0”。
In the following function, the input is the part of an IP address with values from 0 to 255.在下面的 function 中,输入是 IP 地址的一部分,值从 0 到 255。

1) when the value is 1 digit number (0-9) end the input is also 1 digit number (0-9) then don't trim anything if it's 2 digit number (00-09) or 3 digit number (000-009) trim 1 or 2 zeros "0" from the start so the output will be (0-9). 1) 当值为 1 位数字 (0-9) 结束时,输入也是 1 位数字 (0-9),如果是 2 位数字 (00-09) 或 3 位数字 (000-),则不要修剪任何内容009) 从头开始修剪 1 或 2 个零“0”,因此 output 将为 (0-9)。

2) when the value is 2 digit number (10-99) end the input is also 2 digit number (10-99) then don't trim anything if it's 3 digit number (010-099) trim zero "0" from the start so the output will be (10-99). 2) 当值为 2 位数字 (10-99) 结束时,输入也是 2 位数字 (10-99) 然后不要修剪任何东西,如果它是 3 位数字 (010-099) 从开始,所以 output 将是(10-99)。

3) when the value is 3 digit number (100-255) then don't trim anything. 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'
}

You're already making sure only digits 0-9 are accepted, so that's good.您已经确保只接受数字 0-9,这很好。 Pass the validated input value to "expr" to strip leading zeros:将经过验证的输入值传递给 "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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM