bash 如何用换行符替换 : 字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16565487/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:26:10  来源:igfitidea点击:

How do I replace : characters with newline?

linuxbashunix

提问by yatici

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

我查看了一个非常相似的问题,但无法解决问题在 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.

但这取代了 : 与 n。我也试过 tr 但结果相同。我相信 -e 在通过管道传输后不会被看到,因此无法识别新行。

Any help is appreciated.

任何帮助表示赞赏。

回答by pilcrow

echo 'this:is:a:test' | tr : \n

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

任何符合 POSIX 的 tr都将支持\n转义序列。但是,您需要注意引用或转义转义序列(上面的双反斜杠)。

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

-eecho的参数对您的 echo 参数没有影响。

回答by chepner

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 bashextensions to the standard, and may not work in another shell.

我假设您已经在变量中拥有该字符串。这使用参数扩展替换运算符将每个替换:为换行符,该换行符使用带$'...'引号的字符串指定。这两个功能都是bash标准的扩展,可能无法在其他 shell 中使用。

$ foo="this:is:a:test"
$ bar="${foo//:/$'\n'}"
$ echo "$bar"
this
is
a
test

回答by Wolph

Perhaps Perl is an option?

也许 Perl 是一种选择?

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

回答by Bill

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

你不需要,echo -e因为你有\nin sed, not inecho声明。因此,以下应该有效(请注意,我已更改'\n'\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)

另请注意,您不需要转义,:因此以下内容也将起作用(感谢@anishsane)

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

Below is just to reiterate why you need -efor echo

以下仅仅是重申为什么你需要-eecho

$ echo -e "hello \n"
hello

$ echo  "hello \n"
hello \n