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?

2 Answers 2

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)

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'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.