Quantcast
Channel: User Dennis Williamson - Unix & Linux Stack Exchange
Viewing all articles
Browse latest Browse all 61

Answer by Dennis Williamson for Bash: how to get the first number that occurs in a variable's content

$
0
0

I've put your strings in an array so it can easily be iterated for this demonstration.

This uses Bash's builtin regular expression matching.

Only a very simple pattern is required. It's recommended to use a variable to hold the pattern instead of incorporating it directly in the match test. It's essential for more complex patterns.

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

I included the square brackets only to visually set off the numbers.

Output:

[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

To get the numbers without the leading zeroes, the easiest way is to force a base-10 conversion.

echo "$(( 10#${BASH_REMATCH[1]} ))"

Substituting that, the output looks like what you requested:

3000
11
20

Viewing all articles
Browse latest Browse all 61

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>