如何根据重复的模式使用sed删除一堆行?

时间:2011-06-08 08:30:38

标签: shell unix sed

我有一个包含这样内容的文件:

[device]  
type=alpha  
instance=0  

[device]  
type=beta  
instance=1  

[device]  
type=gamma  
instance=2  

我想知道如何删除行

[device]  
type=beta  
instance=1  

我无法在[device]和instance = 2之间使用范围删除,因为它删除了第一个设备部分。

感谢。

1 个答案:

答案 0 :(得分: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