1

I am trying to extract number from string in shell string is "1.69.0"

string="1.69.0"

I am looking for those numbers in 3 different variables like num1=1, num2=69, num3=0.

4 Answers4

5

See here:

str="1.69.0"
IFS=. read -r -a num <<<"$str"
echo "${num[0]}"
echo "${num[1]}"
echo "${num[2]}"
ceving
  • 21,900
  • 13
  • 104
  • 178
1

In bash, it is possible to store your version numbers in a list in the following way:

version="2.3.5-0041"
version_list=( ${version//[-.]/${IFS:0:1}} )
echo "Major release: ${version_list[0]}"
echo "Minor release: ${version_list[1]}"
echo "Patch level  : ${version_list[2]}"
echo "Build number : ${version_list[3]}"
kvantour
  • 25,269
  • 4
  • 47
  • 72
0

How about

if [[ $string =~ ^([[:digit:]]+)[.]([[:digit:]]+)[.]([[:digit:]])$ ]]
then
  first_num=${BASH_REMATCH[1]}
  second_num=${BASH_REMATCH[2]}
  third_num=${BASH_REMATCH[3]}
else
  echo Invalid content: "'$string'" 1>&2
fi

which also would verify that string indeed has the desired format.

user1934428
  • 19,864
  • 7
  • 42
  • 87
0

Maybe

$ eval "m=($(echo $string | tr '.' ' '))"
$ echo ${m[*]}
1 69 0

This assumes all strings are similar '.' separators only

stevea
  • 191
  • 4