bash 在每个字母之间添加空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8696751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add space between every letter
提问by Village
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 !
.
如何在 UTF-8 文档中的每个字符或符号之间添加空格?例如123hello!
变成1 2 3 h e l l o !
。
- I have
BASH
,OpenOffice.org
, andgedit
, 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).
- 我有
BASH
,OpenOffice.org
, 和gedit
,如果其中任何一个可以做到这一点。 - 我不在乎它是否有时会在某些地方留下额外的空间(例如,一个地方有 2 或 3 个空格没有问题)。
回答by SiegeX
Shortest sed
version
最短sed
版本
sed 's/./& /g'
Output
输出
$ echo '123hello!' | sed 's/./& /g'
1 2 3 h e l l o !
Obligatory awk
version
强制awk
版本
awk '=' FS= OFS=" "
Output
输出
$ echo '123hello!' | awk '=' FS= OFS=" "
1 2 3 h e l l o !
回答by sarnold
sed(1)
can do this:
sed(1)
可以这样做:
$ sed -e 's/\(.\)/ /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:
它适用于例如 UTF-8 编码的日语内容:
$ file japanese
japanese: UTF-8 Unicode text
$ sed -e 's/\(.\)/ /g' < japanese
E X I F 中 の 画 像 回 転 情 報 対 応 に よ り 、 一 部 画 像 ( 特 に 『
$
回答by Marc Morin
Since you have bash, I am will assume that you have access to sed. The following command line will do what you wish.
既然你有 bash,我会假设你可以访问 sed。以下命令行将执行您希望的操作。
$ sed -e 's:\(.\): :g' < input.txt > output.txt
回答by angel rengo
sed is ok but this is pure bash
sed 没问题,但这是纯粹的 bash
string=hello
for ((i=0; i<${#string}; i++)); do
string_new+="${string:$i:1} "
done
回答by potong
This might work for you:
这可能对你有用:
echo '1 23h ello ! ' | sed 's/\s*/ /g;s/^\s*\(.*\S\)\s*$//;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.
用空格替换字母之间的空格。
回答by potong
I like these solutions because they do not have a trailing space like the rest here.
我喜欢这些解决方案,因为它们没有像这里其他解决方案一样的尾随空间。
GNU awk:
GNU awk:
echo 123hello! | awk NF=NF FS=
GNU awk:
GNU awk:
echo 123hello! | awk NF=NF FPAT=.
POSIX awk:
POSIX awk:
echo 123hello! | awk '{while(a=substr(##代码##,++b,1))printf b-1?FS a:a}'