Bash script: split word on each letter

I would use grep:

$ grep -o . <<<"StackOver"
S
t
a
c
k
O
v
e
r

or sed:

$ sed 's/./&\n/g' <<<"StackOver"
S
t
a
c
k
O
v
e
r

And if empty space at the end is an issue:

sed 's/\B/&\n/g' <<<"StackOver"

All of that assuming GNU/Linux.


You may want to break on grapheme clusters instead of characters if the intent is to print text vertically. For instance with a e with an acute accent:

  • With grapheme clusters (e with its acute accent would be one grapheme cluster):

    $ perl -CLAS -le 'for (@ARGV) {print for /\X/g}' $'Ste\u301phane'
    S
    t
    é
    p
    h
    a
    n
    e
    

    (or grep -Po '\X' with GNU grep built with PCRE support)

  • With characters (here with GNU grep):

    $ printf '%s\n' $'Ste\u301phane' | grep -o .
    S
    t
    e
    
    p
    h
    a
    n
    e
    
  • fold is meant to break on characters, but GNU fold doesn't support multi-byte characters, so it breaks on bytes instead:

    $ printf '%s\n' $'Ste\u301phane' | fold -w 1
    S
    t
    e
    �
    �
    p
    h
    a
    n
    e
    

On StackOver which only consists of ASCII characters (so one byte per character, one character per grapheme cluster), all three would give the same result.


If you have perl6 in your box:

$ perl6 -e 'for @*ARGS -> $w { .say for $w.comb }' 'cường'       
c
ư
ờ
n
g

work regardless of your locale.