kjbradley
kjbradley

Reputation: 335

Looping over a Bash array: getting the next element in the middle of the loop

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'.

Upvotes: 10

Views: 14585

Answers (3)

Michael Hoffman
Michael Hoffman

Reputation: 34324

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.

Upvotes: 10

glenn jackman
glenn jackman

Reputation: 246764

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

Upvotes: 4

cforbish
cforbish

Reputation: 8819

This should work:

for ((index=0; index < ${#lines_ary[@]}; index++)); do
  line=${lines_ary[index]}
  if [[ ${line} =~ ^.*Release:.*$ ]]; then
    release=${line#*Release: *}
  fi
done

Upvotes: 1

Related Questions