Answer to the question
how to store lines into an array?
With Bash≥4, use mapfile
like so:
mapfile -t array < <(echo "v1.33.4" | egrep -o '[0-9]{1,3}')
With Bash<4, use a loop:
array=()
while read; do
array+=( "$REPLY" )
done < <(echo "v1.33.4" | egrep -o '[0-9]{1,3}')
or, using a single read
statement:
IFS=$'\n' read -r -d '' -a array < <(echo "v1.33.4" | egrep -o '[0-9]{1,3}')
(but note that the return code is 1
).
Answer to solve (what I believe is) your actual problem:
You have a variable where you stored the string v1.33.4
and you want an array that will contain the numbers 1
, 33
and 4
: use the following:
string=v1.33.4
IFS=. read -ra array <<< "${string#v}"
You don't need external utilies at all for that.
Another possibility (that will also validate the format of the string, so I'd say it's the best option for you) is to use a regex:
string=v1.33.4
if [[ "$string" =~ ^v([[:digit:]]+)\.([[:digit:]]+)\.([[:digit:]]+)$ ]]; then
array=( "${BASH_REMATCH[@]:1}" )
else
echo >&2 "Error, bad string format"
exit 1
fi
Then, to loop on the fields of the array:
for field in "${array[@]}"; do
echo "$array"
done