Linux 如何阻止换行符转义旧的gnu-sed命令

Linux 如何阻止换行符转义旧的gnu-sed命令,linux,bash,sed,Linux,Bash,Sed,我试图用多行替换文件中的一行。当我只有一个新行字符(\'$'\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 期望输出 This is a file My Replacement T

我试图用多行替换文件中的一行。当我只有一个新行字符(\'$'\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
期望输出

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 's/TextImLookingFor/My\'$'\nReplacement\'$'\nText/g' /path/to/File.txt
就是它没有按照您期望的方式进行解析

不能在单引号字符串中转义单引号。但是,可以
$'…'
带引号的字符串中转义一个引号(我不确定为什么)

因此,上面的命令不会以这种方式进行分析(如您所料):

相反,它是这样解析的:

[sed] [s/TextImLookingFor/My\]$[\nReplacement\'$]\nText/g' [/path/to/File.txt]
末尾有一个不匹配的单引号和一个不带引号的
\nText/g

这就是你问题的原因

如果您不能仅在替换中使用
\n
(您的
sed
版本不支持此功能),并且您需要使用
$'\n'
,那么您需要使用类似

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

不能在单引号字符串中转义单引号。那不行。你为什么要在这里使用
$'\n'
?仅在替换中使用
\n
是否不符合您的要求?它与第一个命令一起工作+如果我对sed命令使用双引号,那么它将打印出变量而不是实际的新行
sed的/TextImLookingFor/my\nReplacement\nText/'
不适用于您吗?所有'\n'在单引号字符串中打印为'n'?这是什么贝壳?使用
\\n
效果更好吗?这很有效!谢谢你。我没有在您的回复中看到您的$符号:)
[sed] [s/TextImLookingFor/My\]$[\nReplacement\'$]\nText/g' [/path/to/File.txt]
sed 's/TextImLookingFor/My\'$'\nReplacement\\'$'\nText/g' /path/to/File.txt