2016-09-27 85 views
1

如何使用shell命令(SED或AWK)来替换一个段落在文件如下所示:替换文本段落

bala bala ba1 
balabala. 
leave me here. 

this paragraph 
yes, I'm going 
to be replaced 

The rest contains 
should not be replaced. 

更换后:

bala bala ba1 
balaba. 
leave me here. 

New contains, 
I'm replacement! 

The rest contains 
should not be replaced. 

我声明包含在变量$OLD中的原始数据,并将新数据包含在另一个变量$NEW中。

回答

4

假设您拥有一个包含新老段落,变量在

$ echo "$old" 
this paragraph 
yes, I'm going 
to be replaced 

$ echo "$new" 
New contains, 
I'm replacement! 

您可以读取该文件(假设这就是所谓的infile)成猛砸变量和使用参数扩展:

$ contents=$(< infile) 
$ echo "${contents/$old/$new}" 
bala bala ba1 
balabala. 
leave me here. 

New contains, 
I'm replacement! 

The rest contains 
should not be replaced. 

要就地更改文件:

echo "${contents/$old/$new}" > infile.tmp && mv infile.tmp infile 
+0

是的!谢谢,你救了我的一天! – user3593261