Bash:如何获取变量内容中出现的第一个数字

9 bash

如何获得第一个变量数

我有一个变量:

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"
Run Code Online (Sandbox Code Playgroud)

我需要得到数字:

3000
11
20
Run Code Online (Sandbox Code Playgroud)

cuo*_*glm 8

这是一种方法:

echo $STR | grep -o -E '[0-9]+' | head -1 | sed -e 's/^0\+//'
Run Code Online (Sandbox Code Playgroud)

测试:

$ 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
Run Code Online (Sandbox Code Playgroud)


iru*_*var 7

使用 gawk,将记录分隔符设置RS为数字序列。RS可以通过 检索与模式匹配的文本RT。添加0RT强制它为一个数字(从而删除前导零)。打印第一个实例后立即退出

awk -v RS=[0-9]+ '{print RT+0;exit}' <<< "$STR"
Run Code Online (Sandbox Code Playgroud)

或者这里是一个 bash 解决方案

shopt -s extglob
read -r Z _ <<< "${STR//[^[:digit:] ]/}"
echo ${Z##+(0)}
Run Code Online (Sandbox Code Playgroud)


Sve*_*ven 1

查找正则表达式和man grep.

echo $STR | grep -o [0-9]*
Run Code Online (Sandbox Code Playgroud)

要删除前导零,请将其视为数字:

LIT=$(echo $STR | grep -o [0-9]*)
VAL=$(expr $LIT + 0)
echo $VAL
Run Code Online (Sandbox Code Playgroud)