Add space between every letter

旧街凉风 提交于 2019-11-28 21:25:29

sed(1) can do this:

$ sed -e 's/\(.\)/\1 /g' < /etc/passwd
r o o t : x : 0 : 0 : r o o t : / r o o t : / b i n / b a s h 
d a e m o n : x : 1 : 1 : d a e m o n : / u s r / s b i n : / b i n / s h 

It works well on e.g. UTF-8 encoded Japanese content:

$ file japanese 
japanese: UTF-8 Unicode text
$ sed -e 's/\(.\)/\1 /g' < japanese 
E X I F 中 の 画 像 回 転 情 報 対 応 に よ り 、 一 部 画 像 ( 特 に 『 
$ 

Shortest sed version

sed 's/./& /g'

Output

$ echo '123hello!' |  sed 's/./& /g'
1 2 3 h e l l o !

Obligatory awk version

awk '$1=$1' FS= OFS=" "

Output

$ echo '123hello!' |  awk '$1=$1' FS= OFS=" "
1 2 3 h e l l o !

Since you have bash, I am will assume that you have access to sed. The following command line will do what you wish.

$ sed -e 's:\(.\):\1 :g' < input.txt > output.txt

sed is ok but this is pure bash

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

This might work for you:

echo '1 23h ello  !   ' |  sed 's/\s*/ /g;s/^\s*\(.*\S\)\s*$/\1/;l'
1 2 3 h e l l o !$
1 2 3 h e l l o !

In retrospect a far better solution:

sed 's/\B/ /g' file

Replaces the space between letters with a space.

I like these solutions because they do not have a trailing space like the rest here.

GNU awk:

echo 123hello! | awk NF=NF FS=

GNU awk:

echo 123hello! | awk NF=NF FPAT=.

POSIX awk:

echo 123hello! | awk '{while(a=substr($0,++b,1))printf b-1?FS a:a}'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!