bashfor-loop

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


I have a variable like this:

word="Hello!"

I want to make a for loop on each of the characters, one at a time, e.g. first character="H", then character="e", character="l", etc.

The only way I know is to output each character to separate line in a file, then use while read line, but this seems very inefficient.


Solution

  • 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