使用bash迭代数组并收集值

时间:2016-06-13 16:23:42

标签: bash

我想迭代一个数组并使用head(A)收集类别中的所有值。对于每个标题,应该收集值。

myArray=( 'A' '0' 'A' '0' '1' '2' 'A' '0' '1' '2' '3' '4' )

for i in "${myArray[@]}"; do
  result=$(echo "${myArray[myItem]}"|grep -c "[A-Z]");
  while [ "$result" -ne 0 ]; do
      printf '%s: ' "${myArray[myItem]}"
      myItem=$((myItem+1))
      result=$(echo "${myArray[myItem]}"|grep -c "[A-Z]");
  done

  result=$(echo "$i"|grep -c "[0-9]");
  while [ "$result" -ne 0 ]; do
      printf '%s ' "${myArray[myItem]}"
      myItem=$((myItem+1))
      result=$(echo "${myArray[myItem]}"|grep -c "[0-9]");
  done
  echo ""
done

期望的输出:

A: 0
A: 0 1 2
A: 0 1 2 3 4

不幸的是我得到了:

A:
0
A:
0 1 2
A: 0 1 2 3 4

我该怎么办?

第二变体:

#!/bin/bash

myArray=( 'A' '0' 'A' '0' '1' '2' 'A' '0' '1' '2' '3' '4' )

for i in "${myArray[@]}"; do

  result=$(echo "${myArray[myItem]}"|grep -c "[A-Z]");
  while [ "$result" -ne 0 ]; do
    if [ "${myArray[myItem]}" == "A" ]; then
      printf '%s: ' "${myArray[myItem]}"
      myItem=$((myItem+1))
    else
      break
    fi
  done

  result=$(echo "$i"|grep -c "[0-9]");
  while [ "$result" -ne 0 ]; do
    if [ "${myArray[myItem]}" != "A" ]; then
      printf '%s ' "${myArray[myItem]}"
      myItem=$((myItem+1))
    else
      echo ""
      break
    fi
  done
done

期望的输出:

A: 0
A: 0 1 2
A: 0 1 2 3 4

不幸的是我得到了:

A: 0
A: 0 1 2
A: 0 1 2 3 4 ./myTestArray.bash: line 19: [: !=: unary operator expected

./myTestArray.bash: line 19: [: !=: unary operator expected

./myTestArray.bash: line 19: [: !=: unary operator expected

./myTestArray.bash: line 19: [: !=: unary operator expected

./myTestArray.bash: line 19: [: !=: unary operator expected

./myTestArray.bash: line 19: [: !=: unary operator expected

./myTestArray.bash: line 19: [: !=: unary operator expected

我该怎么做才能摆脱错误?

提前谢谢

1 个答案:

答案 0 :(得分:1)

尝试:

myArray=( 'A' '0' 'A' '0' '1' '2' 'A' '0' '1' '2' '3' '4' )

fmt="%s:"
for i in "${myArray[@]}"; do
    case "$i" in
        [A-Z])
            printf "$fmt" "$i"
            fmt='\n%s:'
            ;;
        *)
            printf " %s" "$i"
            ;;
    esac
done
echo ""

这会遍历数组。对于数组中的每个元素$i,它决定它是否是大写字符。如果是,则在行的开头打印,然后是冒号。如果不是,则打印一个空格,然后打印该元素。

这会产生输出:

$ bash script
A: 0
A: 0 1 2
A: 0 1 2 3 4