3

How should I loop through all chars in a string.

My pseudocode

stringVar="abcde"

for var in stringvar
{
   do some things with var
}

result i need
a

b

c

d

I want to loop all the vars but i can only get it to work with a whitespace splitted var like

 stringVar="a b c"


for var in stringVar; do
   echo $var
done;

result

a

b

c

but i cant do it for a string that isnt split with whitespaces.

The question is flagged as duplicate but not one of the answers (with upvotes) is available in the linked questions..

11
  • @alfasin they dont explain how to perform an action on each char. Commented Apr 12, 2015 at 19:13
  • 2
    Yes they do, @SvenB Commented Apr 12, 2015 at 19:14
  • Why is this something that you believe you need to do? Commented Apr 12, 2015 at 19:16
  • read this answer more carefully. stackoverflow.com/questions/10551981/… Commented Apr 12, 2015 at 19:17
  • 1
    Then why wouldn't you just ask about that in the first place? Commented Apr 12, 2015 at 19:32

2 Answers 2

7

You can use read for that:

string="abcde"
while read -n 1 char ; do
    echo "$char"
done <<< "$string"

Using -n 1 read will read one character at a time. However, the input redirection <<< adds a newline to the end of $string.

Sign up to request clarification or add additional context in comments.

7 Comments

this method skips white spaces, unfortunately
can't reproduce
you used echo which creates a new line on each iteration. if you try with printf you'll see that this method skips spaces. here is an example
ok, you have to use IFS= read -n 1 char to read spaces too. example: read-spaces
|
3
stringVar="abcde"
for ((i=1;i<=${#stringVar};i++)); do
  echo ${stringVar:$i-1:1}
done

Output:

a
b
c
d
e

1 Comment

Why not for ((i = 0; i < ${#stringVar}; i++)); do echo ${stringVar:$i:1} ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.