使用sed命令用模式替换多行字符串

问题描述 投票:0回答:2

我想替换内容为多行的字符串。在每一行的末尾,它可以是a / n或\ r \ n,对于缩进,它可以是制表或空格,我不知道。我认为找到字符串的最好方法是使用模式并使用sed替换它。这是文件的内容:

<Element Blabla>        
        A content
        A second content
        A third content
</Element>
<Element TheSearchedElement>        
        A content
        A second content
        A third content
</Element>
<Element Blabla2>        
        A content
        A second content
        A third content
</Element>

我想替换这个块:

<Element TheSearchedElement>        
        A content
        A second content
        A third content
</Element>

通过这个块:

<Element TheSearchedElement>        
        A content
        A second replaced
        A third content
</Element>

我想我应该创建一个变量oldPattern,它包含要查找的模式和一个包含要写入的新模式的变量newPattern。这是我的脚本的内容:

$oldPattern='<Element TheSearchedElement>*A content*A second content*A third*content*</Element>'
$newPattern='<Element TheSearchedElement>/n/tA content/n/tA second replaced/n/tA third*content/n</Element>'
sed -e '/oldPattern/newPattern/' file.conf

问题是输出时出错:script.sh:1:script.sh:= contentA second contentA thirdcontent *:not found script.sh:2:script.sh:= / n / tA content / n / tA第二个替换/ n / tA第三个*内容/ n:未找到sed:-e表达式n°1,char 14:命令后无用的字符

我希望你能帮助我。

string bash shell sed
2个回答
0
投票

您不需要进行多线替换,只需将替换限制在地址范围内:

sed '/^<Element TheSearchedElement>$/,\@^</Element>@{/second/s/content/repl/; }' input

1
投票

你可以尝试一下,让我知道这是否对你有帮助。

awk '/<Element TheSearchedElement>/{print;getline;print;getline;print "        A second replaced";next} 1'  Input_file

如果您想将输出保存到相同的Input_file本身,请执行以下操作(如果您对上述命令的结果感到满意):

awk '/<Element TheSearchedElement>/{print;getline;print;getline;print "        A second replaced";next} 1'  Input_file > temp_file && mv temp_file  Input_file
© www.soinside.com 2019 - 2024. All rights reserved.