开发者

How do I use sed to delete a bunch of lines based on a pattern that repeats?

I have a file with content like this:

[device]  
type=alpha  
instance=0  

[device]  
type=beta  
instance=1  

[device]  
type=gamma  
instance=2  

I am trying to figure how to delete the li开发者_C百科nes

[device]  
type=beta  
instance=1  

I am unable to use range delete between [device] and instance=2 since it removes the first device section.

Thanks.


The easiest way is to first replace all the new lines with some unique character (e.g. !) and then pass it through sed as shown below:

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

Alternatively, you can perform a multi-line search and replace using just sed:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜