![shell腳本在for循環多個文字中回顯文字名稱](https://rvso.com/image/89135/shell%E8%85%B3%E6%9C%AC%E5%9C%A8for%E5%BE%AA%E7%92%B0%E5%A4%9A%E5%80%8B%E6%96%87%E5%AD%97%E4%B8%AD%E5%9B%9E%E9%A1%AF%E6%96%87%E5%AD%97%E5%90%8D%E7%A8%B1.png)
我正在嘗試這樣做
text1="word1 word2 word3"
text2="word4 word5"
text1="word6 word7 word8"
for var in $text1 $text2 $text3
do
echo $var" in "(__?__)
done
預期產出
word1 in text1
word2 in text1
...
word4 in text2
...
word8 in text3
- 腳本將使用破折號 -> 執行,因此不允許使用 bashisms
- 我知道 shell 不是文字處理工具
- 循環是否在迭代之前連接 $text1 $text2 $text3 ?
答案1
text1="word1 word2 word3"
text2="word4 word5"
text3="word6 word7 word8"
set -f #disable globbing in unquoted var expansions (optional)
for i in text1 text2 text3; do
eval "j=\$$i" #i holds name, $j holds the fields
for k in $j; do #k holds a field
echo "$k in $i"
done
done
輸出:
word1 in text1
word2 in text1
word3 in text1
word4 in text2
word5 in text2
word6 in text3
word7 in text3
word8 in text3