brucezepplin
brucezepplin

Reputation: 9752

nested bash loop to print two arrays on same line

Hi I have created two arrays:

$ echo "${prot}"
abc
def
ghi

$ echo "${pos}"
123
456
789

where element n in prot refers to element n in pos. so I want to print the corresponding elements on one line, with one new line per pair.

I am trying to do this with a nested loop, where I split the respective arrays into elements via a newline:

for i in "${!prot[@]}";  do
    for j in "${!pos[@]}";  do
        IFS=$'\n' read -a arr1 <<<"$i"
        IFS=$'\n' read -a arr2 <<<"$j"
        echo $i $j  
    done
done

but this only gives me the last pair. it's one line which is great, but it's not printing them all. what am I doing wrong?

Expected output:

$
    abc 123
    def 456
    ghi 789

I created the arrays in the first place by doing

    for i in *.fasta; do
    IFS=_-. read -ra arr <<<"$i"
    tmp=$(printf "${arr[*]: 0: 1} ${arr[*]: 1: 1} ${arr[*]: -2: 1}")
    fa+="$tmp\n"
    done

   for i in "${fa[@]}"; do
   prot=$(echo -e "$i" | cut -d\  -f 1)
   pos=$(echo -e "$i" | cut -d\ -f 2) 
   done

Upvotes: 1

Views: 2525

Answers (2)

tmp
tmp

Reputation: 1127

First you have to split strings into proper bash arrays:

readarray -t prot_array <<< "$prot"
readarray -t pos_array <<< "$pos"

Then, I would try something like:

for ((i=0; i<${#prot_array[@]}; i++)); do
    echo "${prot_array[i]} ${pos_array[i]}";
done

It's simple solution without nested loops. ${#prot[@]} is the size of the array. The loop displays corresponding elements of both arrays.

Upvotes: 2

David C. Rankin
David C. Rankin

Reputation: 84561

Another way that works even when dealing with arrays of differing length is simply to use a while loop with a counter variable to output the arrays side-by-side so long as both arrays have values:

#!/bin/bash

a1=( 1 2 3 4 5 )
a2=( a b c d e f g )

declare -i i=0

while [ "${a1[i]}" -a "${a2[i]}" ]; do

    printf " %s  %s\n" "${a1[i]}" "${a2[i]}"
    ((i++))

done

exit 0

Output

$ bash arrays_out.sh
 1  a
 2  b
 3  c
 4  d
 5  e

Upvotes: 1

Related Questions