0

I wants to loop thru two strings that has the same delimiter and same number of items in bash shell.

I am currently do this:

string1=s1,s2,s3,s4
string2=a1,a2,a3,a4
IFS=','
count=0
for i in ${string1[@]}
do
    echo $i
    echo $count
    // how can I get each item in string2?
    count=$((count+1))
done

As far as I know, I cannot loop thru two string at the same time. How can I get each item in string 2 inside the loop?

2 Answers 2

1

Extract the fields of each string into separate arrays, then iterate over the indices of the arrays.

IFS=, read -ra words1 <<< "$string1"
IFS=, read -ra words2 <<< "$string2"

for ((idx = 0; idx < ${#words1[@]}; idx++)); do
  a=${words1[idx]}
  b=${words2[idx]}
  echo "$a <=> $b"
done
s1 <=> a1
s2 <=> a2
s3 <=> a3
s4 <=> a4
Sign up to request clarification or add additional context in comments.

Comments

0

You can read from both strings with something like:

#!/bin/bash

string1=s1,s2,s3,s4
string2=a1,a2,a3,a4

count=0
while read item1 && read item2 <&3; do
        echo $((count++)): "$item1:$item2"
done <<< "${string1//,/$'\n'}" 3<<< "${string2//,/$'\n'}"

It's a bit ugly using the ${//} to replace the commas with newlines, so you might prefer:

#!/bin/bash

string1=s1,s2,s3,s4
string2=a1,a2,a3,a4

count=0
while read -d, item1 && read -d, item2 <&3; do
        echo $((count++)): "$item1:$item2"
done <<< "${string1}," 3<<< "${string2},"

That necessitates adding a terminating , on the strings which feels a bit uglier IMO.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.