9

搜索已将文件读入其中的数组 (lines_ary[@]),我试图在文本中查找版本号。这里我在找Release,所以我可以找到后面的版本号。

执行以下循环时,是否有任何方法可以访问 bash 脚本中数组中的下一个元素?

for i in ${lines_ary[@]}; do
 if [ $i == "Release:" ] ; then
  echo ${i+1}
 fi
done

这只是打印出'1',而不是说'4.4'。

4

3 回答 3

9

您需要在数组上的索引而不是数组本身的元素上循环:

for ((index=0; index <= ${#lines_ary[@]}; index++)); do
  if [ "${lines_ary[index]}" == "Release:" ]; then
    echo "${lines_ary[index+1]}"
  fi
done

在元素上使用for x in ${array[@]}循环而不是在其上使用索引。使用变量名i并不是一个好主意,因为i它通常用于索引。

于 2013-06-11T20:56:10.687 回答
4

假设行数组看起来像

array=("line 1" "Release: 4.4" "line 3")

然后你可以这样做:

# 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

输出:

4.4
于 2013-06-11T21:42:42.030 回答
1

这应该有效:

for ((index=0; index < ${#lines_ary[@]}; index++)); do
  line=${lines_ary[index]}
  if [[ ${line} =~ ^.*Release:.*$ ]]; then
    release=${line#*Release: *}
  fi
done
于 2013-06-11T21:44:46.667 回答