How to perform a for loop on each character in a string in Bash?

You can use a C-style for loop:

foo=string
for (( i=0; i<${#foo}; i++ )); do
  echo "${foo:$i:1}"
done

${#foo} expands to the length of foo. ${foo:$i:1} expands to the substring starting at position $i of length 1.


${#var} returns the length of var

${var:pos:N} returns N characters from pos onwards

Examples:

$ words="abc"
$ echo ${words:0:1}
a
$ echo ${words:1:1}
b
$ echo ${words:2:1}
c

so it is easy to iterate.

another way:

$ grep -o . <<< "abc"
a
b
c

or

$ grep -o . <<< "abc" | while read letter;  do echo "my letter is $letter" ; done 

my letter is a
my letter is b
my letter is c

With sed on dash shell of LANG=en_US.UTF-8, I got the followings working right:

$ echo "你好嗎 新年好。全型句號" | sed -e 's/\(.\)/\1\n/g'
你
好
嗎

新
年
好
。
全
型
句
號

and

$ echo "Hello world" | sed -e 's/\(.\)/\1\n/g'
H
e
l
l
o

w
o
r
l
d

Thus, output can be looped with while read ... ; do ... ; done

edited for sample text translate into English:

"你好嗎 新年好。全型句號" is zh_TW.UTF-8 encoding for:
"你好嗎"     = How are you[ doing]
" "         = a normal space character
"新年好"     = Happy new year
"。全型空格" = a double-byte-sized full-stop followed by text description

Tags:

Bash

For Loop