| Newsgroups |
gmane.editors.sed.user |
| Message-ID |
<[email protected]> |
On 2015-02-26 12:12, Lars Noodén [email protected] [sed-users]
wrote:
> Using GNU sed 4.2.2-4ubuntu1 on Ubuntu 14.04 LTS GNU/Linux
>
>
> I have some blocks of text spread over multiple lines and delimited
> by [ and ]. ( See the tail of the message for an example. ) I'd
> like to delete the nth [ ] block. The following pattern will
> delete all [ ] blocks:
>
>
> sed '/^\[$/,/^\]/d' in > out
>
>
> That deletes more than I want deleted. How can I make a sed
> formula or two that only deletes the nth block and leaves the
> others?
Though ugly, the following worked for my basic testing:
bash$ cat del_2nd.sed
/^\[$/,/^\]$/{
/^\[$/{
x
s/$/X/
x
t a
:a
}
x
s/^X\{2\}$/&/
x
T
d
}
bash$ sed -f del_2nd.sed < yourdata.txt
Change the "2" on line 10 to whatever value of N you want.
It works by accumulating one "X" in the hold-space every time a new
block is encountered, and then if there are N "X" characters in the
hold buffer, it should delete the line.
The strange "t a; :a" construct is because any previous successful
substitution is considered unless some other "t" or "T" command has
been issued since that substitution. So it's a NOOP to clear the
"has a successful substitution happened yet" flag so that the
"T" (bail on this script by jumping to the end if we're not in an
Nth block). Sigh.
-tkc