0

I'm having a [very bad] blonde moment, and would like to know how I can have a changing variable name inside the following snippet of code:

sentence="This is   a sentence containing f@#cy |3tt3r5."
for word in $sentence
do
    echo $word
done

Ideally I would like to have each of the words in the $sentence variable be held my a unique variable. So for example echo $word_1 would print "This" and echo $word_5 would print "containing" ... etc.

Should I be using arrays?

Q: How can I make a variable that keeps on changing i.e. word_1 word_2.. word_n until the for loop is complete.

3kstc
  • 1,871
  • 3
  • 29
  • 53
  • 1
    Yeah, you could say `sentence=(This is a sentence containing 'f@#cy' '|3tter5.')` and loop over `"${sentence[@]}"` but you need to quote any token with shell metacharacters in it (and actually might want to quote each token). – tripleee Oct 06 '15 at 03:29
  • @triplee Still having the blonde moment- `${sentence[@]}` why would I need to quote it ie `"${sentence[@]}"` and not `${sentence[@]}`? Also "${sentence[@]}" would be an array named "sentence"? – 3kstc Oct 06 '15 at 03:36
  • 1
    That's the syntax, yeah. The quotes are part of that syntax. – tripleee Oct 06 '15 at 03:38
  • 2
    http://stackoverflow.com/questions/10586153/split-string-into-an-array-in-bash might help you use array – zedfoxus Oct 06 '15 at 03:40

0 Answers0