如何获取变量的第一个数量
我有一个变量:
STR="My horse weighs 3000 kg but the car weighs more"
STR="Maruska found 000011 mushrooms but only 001 was not with meat"
STR="Yesterday I almost won the lottery 0000020 CZK but in the end it was only 05 CZK"
我需要获取数字:
3000
11
20
答案1
这是一种方法:
echo $STR | grep -o -E '[0-9]+' | head -1 | sed -e 's/^0\+//'
测试:
$ STR="My horse weighs 3000 kg but the car weighs more"
$ echo $STR | grep -o -E '[0-9]+' | head -1 | sed -e 's/^0\+//'
3000
$ STR="Maruska found 000011 mushrooms but only 001 was not with meat"
$ echo $STR | grep -o -E '[0-9]+' | head -1 | sed -e 's/^0\+//'
11
$ STR="Yesterday I almost won the lottery 0000020 CZK but in the end it was only 05 CZK"
$ echo $STR | grep -o -E '[0-9]+' | head -1 | sed -e 's/^0\+//'
20
答案2
使用 gawk,将记录分隔符设置RS
为数字序列。RS
可以通过 检索与模式匹配的文本RT
。添加0
到RT
以强制其为数字(从而删除前导零)。打印第一个实例后立即退出
awk -v RS=[0-9]+ '{print RT+0;exit}' <<< "$STR"
或者这是一个 bash 解决方案
shopt -s extglob
read -r Z _ <<< "${STR//[^[:digit:] ]/}"
echo ${Z##+(0)}
答案3
如果您的实现grep
没有-o
或者您没有使用 Bash,您可以执行以下操作:
printf "%.0f\n" $(printf "%s" "$string"|sed 's/^[^0-9]*//;s/[^0-9].*$//')
答案4
我已将您的字符串放入一个数组中,以便可以轻松地对该演示进行迭代。
这使用了 Bash 的内置正则表达式匹配。
只需要一个非常简单的模式。建议使用变量来保存模式,而不是直接将其合并到匹配测试中。这对于更复杂的模式至关重要。
str[0]="My horse weighs 3000 kg but the car weighs more"
str[1]="Maruska found 000011 mushrooms but only 001 was not with meat"
str[2]="Yesterday I almost won the lottery 0000020 CZK but in the end it was only 05 CZK"
patt='([[:digit:]]+)'
for s in "${str[@]}"; do [[ $s =~ $patt ]] && echo "[${BASH_REMATCH[1]}] - $s"; done
我添加方括号只是为了在视觉上衬托数字。
输出:
[3000] - My horse weighs 3000 kg but the car weighs more
[000011] - Maruska found 000011 mushrooms but only 001 was not with meat
[0000020] - Yesterday I almost won the lottery 0000020 CZK but in the end it was only 05 CZK
要获取不带前导零的数字,最简单的方法是强制进行以 10 为基数的转换。
echo "$(( 10#${BASH_REMATCH[1]} ))"
替换它,输出看起来像您所要求的:
3000
11
20