簡體   English   中英

如何循環通過 bash shell 中的兩個拆分字符串?

[英]How do I loop thru two split strings in bash shell?

我想遍歷兩個在 bash shell 中具有相同分隔符和相同項目數的字符串。

我目前正在這樣做:

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

據我所知,我不能同時遍歷兩個字符串。 如何在循環內獲取字符串 2 中的每個項目?

將每個字符串的字段提取到單獨的數組中,然后遍歷數組的索引

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

您可以使用以下內容從兩個字符串中讀取:

#!/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'}"

使用${//}將逗號替換為換行符有點難看,因此您可能更喜歡:

#!/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},"

這需要在 IMO 感覺有點丑陋的琴弦上添加一個,終止符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM