shell script echo text name in for looping multiple texts Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of shell script echo text name in for looping multiple texts without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am trying to do this

text1="word1 word2 word3"
text2="word4 word5"
text1="word6 word7 word8"

for var in $text1 $text2 $text3
do
  echo $var" in "(__?__)
done

expected output

word1 in text1
word2 in text1
...
word4 in text2
...
word8 in text3
  1. script will be executed with dash -> so no bashisms allowed
  2. I am aware that shell is not a tool for text processing
  3. does the loop concatenate $text1 $text2 $text3 before iterating or not ?

Answer

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

Output:

word1 in text1
word2 in text1
word3 in text1
word4 in text2
word5 in text2
word6 in text3
word7 in text3
word8 in text3
We are here to answer your question about shell script echo text name in for looping multiple texts - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji