Searching an array (lines_ary[@]) which has read a file into it, I'm trying to find a version number in the text. Here I am looking for Release, so I can find the version number that follows.
Is there any way to access the next element in an array in a bash script when doing the following loop?
for i in ${lines_ary[@]}; do
if [ $i == "Release:" ] ; then
echo ${i+1}
fi
done
This just prints out '1', rather than say '4.4'.
You need to loop on an index over the array rather than the elements of the array itself:
for ((index=0; index < ${#lines_ary[@]}; index++)); do
if [ "${lines_ary[index]}" == "Release:" ]; then
echo "${lines_ary[index+1]}"
fi
done
Using for x in ${array[@]}
loops over the elements rather than an index over it. Use of the variable name i
is not such a good idea because i
is commonly used for indexes.
Assuming the lines array looks something like
array=("line 1" "Release: 4.4" "line 3")
Then you can do:
# loop over the array indices
for i in "${!array[@]}"; do
if [[ ${array[i]} =~ Release:\ (.+) ]]; then
echo "${BASH_REMATCH[1]}" # the text in the capturing parentheses
break
fi
done
output:
4.4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With