2011-06-08 53 views
1

我有这样的内容文件:如何根据重复的模式使用sed删除一堆行?

[device] 
type=alpha 
instance=0 

[device] 
type=beta 
instance=1 

[device] 
type=gamma 
instance=2 

我试图找出如何删除线

[device] 
type=beta 
instance=1 

我无法使用[装置]和实例之间的范围内删除= 2因为它删除了第一个设备部分。

谢谢。

回答

1

最简单的方法是,首先取代所有的一些独特性质的新线(例如!),然后将其穿过的sed,如下图所示:

tr '\n' '!' < file.txt | sed 's/\[device\]!type=beta!instance=1//g' | tr '!' '\n' 

或者,你可以只用sed执行multi-line search and replace

sed -n ' 
# if the first line copy the pattern to the hold buffer 
1h 
# if not the first line then append the pattern to the hold buffer 
1!H 
# if the last line then ... 
$ { 
     # copy from the hold to the pattern buffer 
     g 
     # do the search and replace 
     s/\[device\]\ntype=beta\ninstance=1//g 
     # print 
     p 
} 
' file.txt