How do I replace : characters with newline?

后端 未结 4 1115
野的像风
野的像风 2020-12-22 08:05

I looked at a very similar question but was unable to resolve the issue Replace comma with newline in sed

I am trying to convert : characters in a strin

相关标签:
4条回答
  • 2020-12-22 08:22

    You do not need echo -e because you have \n in sed, not in echo statement. So, the following should work (note that I have changed '\n' to \n):

    echo -e 'this:is:a:test' | sed "s/\:/\n/g"
    

    or

    echo  'this:is:a:test' | sed "s/\:/\n/g"
    

    Also note that you do not need to escape : so the following will work too (thanks to @anishsane)

    echo  'this:is:a:test' | sed "s/:/\n/g"
    

    Below is just to reiterate why you need -e for echo

    $ echo -e "hello \n"
    hello
    
    $ echo  "hello \n"
    hello \n
    
    0 讨论(0)
  • 2020-12-22 08:24
    echo 'this:is:a:test' | tr : \\n
    

    Any POSIX-compliant tr will support the \n escape sequence. You need to take care to quote or escape the escape sequence, however (double backslash above).

    The -e argument to echo has no effect on your argument to echo.

    0 讨论(0)
  • 2020-12-22 08:27

    Perhaps Perl is an option?

    echo -e 'this:is:a:test' | perl -p -e 's/:/\n/g'
    
    0 讨论(0)
  • 2020-12-22 08:28

    I'll presume that you have the string in a variable already. This uses the parameter expansion substitution operator to replace every : with a newline, which is specified using a $'...'-quoted string. Both features are bash extensions to the standard, and may not work in another shell.

    $ foo="this:is:a:test"
    $ bar="${foo//:/$'\n'}"
    $ echo "$bar"
    this
    is
    a
    test
    
    0 讨论(0)
提交回复
热议问题