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..
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.
stringVar="abcde"
for ((i=1;i<=${#stringVar};i++)); do
echo ${stringVar:$i-1:1}
done
Output:
a b c d e
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With