Henri74
Henri74

Reputation: 13

How to read numbers into variables from string

I have strings that look like this:

user@pc: $ example="bla bla bla (m=100, number of steps=1.05)"

How can I read the values 100 and 1.05 into two variables that I can use them afterwards?

user@pc: $ echo $A
100
user@pc: $ echo $B
1.05

Upvotes: 0

Views: 173

Answers (2)

ctac_
ctac_

Reputation: 2471

Another way with bash

example="bla bla bla (m=100, number of steps=1.05)"
var=(${example//[^0-9 \.]})
for i in ${var[@]};do
  echo $i
done

Upvotes: 0

iBug
iBug

Reputation: 37217

Use an extra tool like grep to extract numbers first:

NUMS=($(grep -Eo '[0-9]+(\.[0-9]+)?' <<<"${example}"))
A=${NUMS[0]}
B=${NUMS[1]}

Upvotes: 1

Related Questions