1

In attempting to use ed to delete lines around a certain pattern I've been driving my self nut ts.

What I'd like to do is match a pattern, and then delete lines around it.

I've tried several variations

ed test.txt <<<< $'/pattern/-1,+1d\nwq'
ed test.txt <<<< $'(/pattern/-1,+1)d\nwq'
ed test.txt <<<< $'/pattern/-,+1d\nwq'
ed test.txt <<<< $'(/pattern/-,+1)d\nwq'
ed test.txt <<<< $'/pattern/-,+d\nwq'
ed test.txt <<<< $'(/pattern/-,+)d\nwq'

None of which worked. How is it done?

David Jones
  • 4,766
  • 3
  • 32
  • 45
Catskul
  • 17,916
  • 15
  • 84
  • 113

2 Answers2

2

Using a semicolon, ;, will set the current line, ., before processing the second address. This makes the second address relative to the first, which is almost what you want:

/pattern/-;+2d

Because the second address is relative to the first, and not relative to the pattern, we have to use +2 to address the lines one-before and one-after the pattern.

(Note that /pattern/- is shorthand for /pattern/-1)

David Jones
  • 4,766
  • 3
  • 32
  • 45
1

I figured it out after much trial and error, though I can't seem to find any documentation that would have told me this. It appears that each line reference must be made to a separate pattern match reference, and so the trick is to give the pattern twice.

 ed test.txt <<<< $'/pattern/-,/pattern/+d\nwq'
Catskul
  • 17,916
  • 15
  • 84
  • 113