5

I have the following grep command

echo v1.33.4 |  egrep -o '[0-9]{1,3}'

which returns:

1
33
4

In Bash-Script I'd like to but those line seperated numbers into an array. I tried to assign it directly to a variable and run a for loop over it. But the echo within the loop only yields the first number 1

xetra11
  • 7,671
  • 14
  • 84
  • 159

2 Answers2

4

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
gniourf_gniourf
  • 44,650
  • 9
  • 93
  • 104
3
#Storing it in an array
array=($(echo v1.33.4 |  egrep -o '[0-9]{1,3}' ))

#Printing an array
for i in ${array[@]}; do echo "$i"; done
1
33
4

Side note: If you wish to convert multiline o/p into one line then

echo v1.33.4 |  egrep -o '[0-9]{1,3}' |paste -sd' '
1 33 4
P....
  • 17,421
  • 2
  • 32
  • 52
  • 1
    Nice! But a pure `bash` solution like @gniourf_gniourf answer would be more efficient.Cheers! – Inian Sep 21 '16 at 09:08
  • Note that you're not defining an array. You'll need: `array=( $(echo v1.33.4 | egrep -o '[0-9]{1,3}' ) )`. But then, this solution is an antipattern, as it's subject to word splitting and pathname expansions. – gniourf_gniourf Sep 21 '16 at 09:11