7

我在谷歌上搜索了很多。我只想要这一行:

echo "Replace <newLine> it by <newLine> NEWLINE <newLine> in my OSX terminal <newLine> and bash script" | sed -e 's/<newLine>/\n/g'

在我的 osx 终端和我的 bash 脚本中工作。我不能用sed这个吗?还有另一种单线解决方案吗?

4

3 回答 3

18

这是使用 sed

echo "Replace <newLine> it by <newLine> NEWLINE <newLine> in my OSX terminal <newLine> and bash script" | sed 's/<newLine>/\'$'\n/g'

这是一篇解释原因的博文 - https://nlfiedler.github.io/2010/12/05/newlines-in-sed-on-mac.html

于 2012-05-07T21:03:41.967 回答
4

仅使用 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

这里有一个简单的解释 - 语法类似于 sed 的替换语法,但您使用双斜杠 ( //) 来表示替换字符串的所有实例。否则,仅替换第一次出现的字符串。

于 2012-05-07T21:00:50.103 回答
1

这可能对您有用:

echo "Replace <newLine> it by <newLine> NEWLINE <newLine> in my OSX terminal <newLine> and bash script" |
sed 'G;:a;s/<newLine>\(.*\(.\)\)$/\2\1/;ta;s/.$//' 
Replace 
 it by 
 NEWLINE 
 in my OSX terminal 
 and bash script

编辑: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>\(.*\(.\)\)$/\2\1/' -e 'ta' -e 's/.$//' 
Replace 
 it by 
 NEWLINE 
 in my OSX terminal 
 and bash script

还有一种方式:

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
于 2012-05-07T23:10:42.810 回答