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

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


You can use a C-style for loop:

foo=stringfor (( 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.


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'Helloworld

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


${#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"abc

or

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