7

I am trying to iterate through a string taken as an input through the read command. I'm trying to output the number of each letter and each letter It should then use a loop to output each letter in turn. For example, if the user enters "picasso", the output should be:

Letter 1: p Letter 2: i Letter 3: c Letter 4: a Letter 5: s Letter 6: s Letter 7: o

Here is my current code:

#!/bin/bash

# Prompt a user to enter a word and output each letter in turn.


read -p "Please enter a word: " word

for i in $word
do
 echo "Letter $i: $word"
done

Should I be placing the input to an array? I'm still new to programming loops but I'm finding it impossible to figure out the logic.

Any advice? Thanks.

  • 1
    Have a look [here](http://stackoverflow.com/questions/10551981/how-to-perform-a-for-loop-on-each-character-in-a-string-in-bash) – mauro Feb 08 '16 at 07:22

3 Answers3

16

Combining answers from dtmilano and patrat would give you:

read -p "Please enter a word: " word

for i in $(seq 1 ${#word})
do
 echo "Letter $i: ${word:i-1:1}"
done

${#word} gives you the length of the string.

oliv
  • 11,216
  • 19
  • 37
6

Use the substring operator

 ${word:i:1}

to obtain the i'th character of word.

Diego Torres Milano
  • 57,580
  • 7
  • 101
  • 124
2

Check out seq mechanism in bash

For example:

seq 1 10

Will give you

1 2 3 4 5 6 7 8 9 10

You can try with letters

echo {a..g}

Result

 a b c d e f g

Now you should handle your problem

patrat
  • 31
  • 3