Bash:変数の内容に表示される最初の数字を取得する方法

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"

数字を調べる必要があります。

3000
11
20

ベストアンサー1

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

おすすめ記事