Add space between every letter

前端 未结 6 1323
感情败类
感情败类 2020-12-09 03:54

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
相关标签:
6条回答
  • 2020-12-09 04:38

    sed is ok but this is pure bash

    string=hello
    for ((i=0; i<${#string}; i++)); do
        string_new+="${string:$i:1} "
    done
    
    0 讨论(0)
  • 2020-12-09 04:39

    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 !
    
    0 讨论(0)
  • 2020-12-09 04:40

    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}'
    
    0 讨论(0)
  • 2020-12-09 04:41

    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
    
    0 讨论(0)
  • 2020-12-09 04:46

    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.

    0 讨论(0)
  • 2020-12-09 04:49

    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 中 の 画 像 回 転 情 報 対 応 に よ り 、 一 部 画 像 ( 特 に 『 
    $ 
    
    0 讨论(0)
提交回复
热议问题