More sed

Aug 16, 2007

So, if you come from the world of Perl, like I do, you’re probably very familiar with the usage of regular expressions to match (m/(foo)bar(baz)/) and replace (s/foo(bar)/baz$1/) strings. sed acts upon lines and often you want to delete a range of lines. For the following regex, I had a document something like this:

<Recording modeType="foo">
    <foo>bar</foo>
    <baz>qux</baz>
</Recording>
<Recording modeType="fp">
    <foo>bar</foo>
    <baz>qux</baz>
</Recording>
<Recording modeType="bar">
    <foo>bar</foo>
    <baz>qux</baz>
</Recording>
…and I wanted to remove any of the blocks of modeType ‘fp’. To do so, I tell sed to find lines with the modeType of 'fp’, and a subsequent line with a closing 'Recording’ tag and then ’d'elete them all:

sed -i -e '/modeType="fp"/,/Recording&gt;/d'

Simple. The more you get to know it, the more awesome sed is.