Home > Software design >  How do I loop thru two split strings in bash shell?
How do I loop thru two split strings in bash shell?

Time:05-18

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?

CodePudding user response:

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

CodePudding user response:

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.

  • Related