0x2a.at

... and their answer to everything

Articles tagged with'shell'

sed - non greedy matching

posted on 2008-07-08, author: Christoph Sieghart

I just needed non greedy matching in sed and the man page had nothing to say about it (I was hoping for a simple flag, but nada).

As do all other regexp engines I know of, sed uses greedy matching per default. The trick to get non greedy matching in sed is to match all characters excluding the one that terminates the match. I know, a no-brainer, but I wasted precious minutes on it and shell scripts should be, after all, quick and easy.

So in case somebody else might need it:

Greedy matching:

% echo "<b>foo</b>bar" | sed 's/<.*>//g'
bar

Non greedy matching:

% echo "<b>foo</b>bar" | sed 's/<[^>]*>//g'
foobar
tag: shell