waJe
waJe

Reputation: 13

Iterating over an array with bash and collecting values

I want to iterate over an array and collect all values in a category with a head (A). For every header the values should be collected.

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

Desired output:

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

Unfortunately I get:

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

What should I do?

Second Variant:

#!/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

Desired output:

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

Unfortunately I get:

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

What should I do to get rid of errors?

Thx in advance

Upvotes: 1

Views: 44

Answers (1)

John1024
John1024

Reputation: 113834

Try:

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 ""

This iterates through the array. For each element $i in the array, it decides if it is an upper case character or not. If it is, it is printed at the beginning of a line and followed by a colon. If it is not, a space is printed followed by the element.

This produces the output:

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

Upvotes: 1

Related Questions