Home Ask Login Register

Developers Planet

Your answer is one click away!

Jordan Glander February 2016

How to iterate through each letter in a string in Unix Shell

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:


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

read -p "Please enter a word: " word

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

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.


patrat February 2016

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}


 a b c d e f g

Now you should handle your problem

Diego Torres Milano February 2016

Use the substring operator


to obtain the i'th character of word.

oliv February 2016

Combining answers from dtmilano and patrat would give you:

read -p "Please enter a word: " word

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

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

Post Status

Asked in February 2016
Viewed 2,422 times
Voted 13
Answered 3 times


Leave an answer

Quote of the day: live life