Add space between every letter

ぃ、小莉子 提交于 2020-01-09 19:06:33

问题


How can I add spaces between every character or symbol within a UTF-8 document? E.g. 123hello! becomes 1 2 3 h e l l o !.

  • I have BASH, OpenOffice.org, and gedit, if any of those can do that.
  • I don't care if it sometimes leaves extra spaces in places (e.g. 2 or 3 spaces in a single place is no problem).

回答1:


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 中 の 画 像 回 転 情 報 対 応 に よ り 、 一 部 画 像 ( 特 に 『 
$ 



回答2:


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 !



回答3:


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



回答4:


sed is ok but this is pure bash

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



回答5:


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.




回答6:


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


来源:https://stackoverflow.com/questions/8696751/add-space-between-every-letter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!