Looping over a Bash array: getting the next element in the middle of the loop
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
This should work:
for ((index=0; index < ${#lines_ary[@]}; index++)); do
line=${lines_ary[index]}
if [[ ${line} =~ ^.*Release:.*$ ]]; then
release=${line#*Release: *}
fi
done
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.