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

答え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

関連情報