How do I replace : characters with newline?

2020-02-15 08:15发布

问题:

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 string. This is what I tried:

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

but this replaces : with n. I tried tr too but had the same result. I believe the -e is not seen after being piped so new line is not recognized.

Any help is appreciated.

回答1:

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.



回答2:

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


回答3:

Perhaps Perl is an option?

echo -e 'this:is:a:test' | perl -p -e 's/:/\n/g'


回答4:

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


标签: linux bash unix