我想遍歷兩個在 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 中的每個專案?
uj5u.com熱心網友回復:
將每個字串的欄位提取到單獨的陣列中,然后遍歷陣列的索引。
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
uj5u.com熱心網友回復:
您可以使用以下內容從兩個字串中讀取:
#!/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 感覺有點丑陋。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/477077.html
