using sed - how do I delete lines above and below a match?

using sed - I need to delete one line above and one line below any line with "ldots" on it.

In the example below all of the lines with "\backslash" and all the lines with "\end_layout" have to be deleted. There are other lines with "\end_layout" that need to stay so that's why I can't do something like:
sed -e 's/\\end_layout//'

Sorry I missed the fact that you want the line inbetween to stay. Sounds like you are cleaning out formatting tags from around matching lines. Mine would take the "ldots" line too. Here's the correction and, as you asked, an explanation also.

This is a bit of an extreme example for sed (I would use either ed or ex myself) since they are not stream oriented and can back track in the file. That's why my earlier example didn't work. I was thinking in 'ed". All the same here is your result with an explanation:

-n "do not print unless I tell you to"
-e '1h' "if this is the first line initialize the hold buffer with the line
-e '1!H' "if this is not the first line then ADD the line to the hold buffer
-e '/ldots/{...}' "if the current line has /ldots/ in it then p-print, get the next line, another next line
reinitialize the hold buffer, and delete the pattern buffer" The delete is so we cycle
to the top
-e 1b "if we are on the first line then jump to the end" need this to handle the special case
of the first line containing your search string (ldots)
-e 'x;P' "otherwise exchange the current line with the hold buffer and 1 line of the hold buffer

Only reason this works is you only want to get a single line above and below. If you wanted to do more lines you would have to resort to using 'ed' or some other scripting language.

Doc..

0

ibanjaAuthor Commented: 2007-04-11

ahoffmann,

thanks for the input but I could not get this to work. It was scrambling the document somehow. I created a short sedTest doc by running "grep -A1 -B1 ldots sampleDoc.lyx > sedTest" which produces the exact same output as in my original question - dumped to the file named sedTest. I then ran line that you gave and got the following:

That is perfect. It works and thanks so much for the explanation. That clearifies a few questions I have had about how to use some of the options in sed, especially the h and the n. I could never get them to work and didn't have any good examples to compare to.