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:

#!/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.

Answers


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}

Result

 a b c d e f g

Now you should handle your problem


Diego Torres Milano February 2016

Use the substring operator

 ${word:i:1}

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})
do
 echo "Letter $i: ${word:i-1:1}"
done

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

Post Status

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

Search




Leave an answer