Bash:如何在osx bash中用换行替换字符串?

时间:2012-05-07 20:52:54

标签: bash sed

我正在谷歌搜索它。我只想要这一行:

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吗?还有另一种解决方案吗?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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的替换语法,但是您使用双斜杠(//)来指示替换字符串的所有实例。否则,只替换第一次出现的字符串。

答案 2 :(得分: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不接受多个命令,请参阅here

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