for ループ 複数テキストのシェルスクリプト エコテキスト名

for ループ 複数テキストのシェルスクリプト エコテキスト名

私はこれをしようとしています。

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
  1. スクリプトはダッシュ -> を使用して実行されるため、bashism は許可されません。
  2. シェルがテキスト処理ツールではないことを知っています。
  3. ループは繰り返す前に $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

おすすめ記事