Bash:如何在 osx bash 中用新行替换字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10488963/
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
Bash: How can I replace a string by new line in osx bash?
提问by Rodrigo
I am googling it a lot. I only want that this line:
我在谷歌上搜索了很多。我只想要这一行:
echo "Replace <newLine> it by <newLine> NEWLINE <newLine> in my OSX terminal <newLine> and bash script" | sed -e 's/<newLine>/\n/g'
works in my osx terminal and in my bash script. I can't use sedfor this? Is there another one line solution?
在我的 osx 终端和我的 bash 脚本中工作。我不能用sed这个?有另一种单线解决方案吗?
回答by xeor
Here is using sed
这里是使用 sed
echo "Replace <newLine> it by <newLine> NEWLINE <newLine> in my OSX terminal <newLine> and bash script" | sed 's/<newLine>/\'$'\n/g'
And here is a blogpost explaining why - https://nlfiedler.github.io/2010/12/05/newlines-in-sed-on-mac.html
这是一篇解释原因的博客文章 - https://nlfiedler.github.io/2010/12/05/newlines-in-sed-on-mac.html
回答by spinlok
Using bash only:
仅使用 bash:
STR="Replace <newLine> it by <newLine> NEWLINE <newLine> in my OSX terminal <newLine> and bash script"
$ echo ${STR//<newLine>/\n}
Replace \n it by \n NEWLINE \n in my OSX terminal \n and bash script
$ echo -e ${STR//<newLine>/\n}
Replace
it by
NEWLINE
in my OSX terminal
and bash script
A quick explanation here - the syntax is similar to sed's replacement syntax, but you use a double slash (//) to indicate replacing all instances of the string. Otherwise, only the first occurrence of the string is replaced.
这里有一个快速解释 - 语法类似于 sed 的替换语法,但您使用双斜杠 ( //) 来表示替换字符串的所有实例。否则,仅替换第一次出现的字符串。
回答by potong
This might work for you:
这可能对你有用:
echo "Replace <newLine> it by <newLine> NEWLINE <newLine> in my OSX terminal <newLine> and bash script" |
sed 'G;:a;s/<newLine>\(.*\(.\)\)$//;ta;s/.$//'
Replace
it by
NEWLINE
in my OSX terminal
and bash script
EDIT: OSX doesn't accept multiple commands see here
编辑:OSX 不接受多个命令,请参见此处
echo "Replace <newLine> it by <newLine> NEWLINE <newLine> in my OSX terminal <newLine> and bash script" |
sed -e 'G' -e ':a' -e 's/<newLine>\(.*\(.\)\)$//' -e 'ta' -e 's/.$//'
Replace
it by
NEWLINE
in my OSX terminal
and bash script
Yet another way:
还有一种方式:
echo "Replace <newLine> it by <newLine> NEWLINE <newLine> in my OSX terminal <newLine> and bash script" |
sed $'s|<newLine>|\\n|g'
Replace
it by
NEWLINE
in my OSX terminal
and bash script

