【问题标题】:Looping over a Bash array: getting the next element in the middle of the loop遍历 Bash 数组:获取循环中间的下一个元素
【发布时间】:2013-06-07 20:40:56
【问题描述】:

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

在执行以下循环时,有什么方法可以访问 bash 脚本中数组中的下一个元素?

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

这只是打印出“1”,而不是“4.4”。

【问题讨论】:

  • 仅供参考 ${i+1} 表示如果 i 未设置(即打印空字符串),则打印 $i 的值,但打印加号后面的单词(在这种情况下, "1") 否则。加号是使用替代值运算符。

标签: bash loops for-loop element


【解决方案1】:

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

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 通常用于索引。

【讨论】:

  • 感谢您的快速响应。该行同时包含“Release:”+“4.4”,因此它们被视为此代码中的一个元素。有什么想法吗?
【解决方案2】:

假设行数组看起来像

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

【讨论】:

    【解决方案3】:

    这应该可行:

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

    【讨论】:

      猜你喜欢
      • 2011-01-11
      • 2022-09-30
      • 2010-12-20
      • 1970-01-01
      • 1970-01-01
      • 2012-05-24
      • 2020-12-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多