如何停止换行字符从转义OLD gnu sed命令

我试图用多行replace文件中的一行。 当我只有一个新的行char(\'$'\ n)。 它工作得很好,但是当我使用其中两个,它逃脱我的sed和该文件不会再运行。

sed 's/TextImLookingFor/My\'$'\nReplacement\'$'\nText/g' /path/to/File.txt 

FILE.TXT:

 This is a file TextImLookingFor look at all this text 

DesiredOutput

 This is a file My Replacement Text look at all this text 

实际产出

 unexpected EOF while looking for matching '''' syntax error: unexpected end of file 

使用较旧的BSD sed,你可以这样做:

 sed $'s/TextImLookingFor/My\\\nReplacement\\\nText/' file This is a file My Replacement Text look at all this text 

这应该与新的GNU-SED一起工作。 不过更新的gnu-sed可能只需要:

 sed 's/TextImLookingFor/My\nReplacement\nText/' file 

这可能适用于你(GNU sed):

 sed '/TextImLookingFor/c\My\nReplacement\nText' file 

这个命令的问题

 sed 's/TextImLookingFor/My\'$'\nReplacement\'$'\nText/g' /path/to/File.txt 

是它不解析你期望的方式。

不能在单引号字符串中转义单引号。 你可以在一个$'...'引用的字符串里面转义一个单引号(但我不太清楚为什么)。

所以上面的命令不会以这种方式解析(如你所期望的):

 [sed] [s/TextImLookingFor/My\'$[\nReplacement\'$]\nText/g] [/path/to/File.txt] 

相反,它解析这种方式:

 [sed] [s/TextImLookingFor/My\]$[\nReplacement\'$]\nText/g' [/path/to/File.txt] 

在最后有一个不匹配的单引号和一个不带引号的\nText/g位。

这是你的问题的原因。

如果你不能只是用你的替换(你的版本的sed不支持),你需要使用$'\n'那么你将需要使用类似

 sed 's/TextImLookingFor/My\'$'\nReplacement\\'$'\nText/g' /path/to/File.txt