sed, delete from MarkA up to but not include MarkB

2

1

Expression in math term, I'd like to delete a region of [MarkA,MarkB). I.e., the deletion happens right when the keyword MarkA is encountered, all the way to keyword MarkB, but not including that line (the line including MarkB keyword is left untouched).

Is it possible to do so in sed?

Say my MarkA is ^3, and MarkB is 7,

$ seq 9 | sed '/^3/,/7/d'
1
2
8
9

It will get my 7 deleted but I want to preserve it.

To be more precise, I can accurately locate MarkA (e.g. ^3), but I want to delete up to the first MarkB. I.e.,

seq 19 | sed '/^3/,/7/d'

is what I'm looking for if the 7 line is not deleted.

xpt

Posted 2015-11-12T17:22:16.600

Reputation: 5 548

I think I understand what you're asking, but can you give a concrete example? It can be made up, but a sample input and the expected output. – blm – 2015-11-12T17:26:47.787

https://github.com/choroba/small-scripts/blob/master/betw – choroba – 2015-11-12T17:48:16.763

@choroba, almost, but I want do delete them but preserve the rest. your script just preserve them but delete the rest. – xpt – 2015-11-12T17:53:18.627

@xpt: That's why I only commented, not answered your question. – choroba – 2015-11-12T17:55:49.700

Answers

3

Using sed

This deletes the range up to but not including the last line in the range:

$ seq 9 | sed '/^3/,/7/{/7/p;d}'
1
2
7
8
9

As before, /^3/,/7/ selects the whole range, inclusive of /7/. And, as before, that range gets deleted with the d command. However, before we delete, we check to see if the line contains /7/ and, in that case, we print it with the p command.

Using awk

awk offers much flexibility. Here, we use a variable f as a flag to decide if lines should be printed:

$ seq 9 | awk '/^3/{f=1} /7/{f=0} !f'
1
2
7
8
9

John1024

Posted 2015-11-12T17:22:16.600

Reputation: 13 893