[TUHS] BRE Grouping in Sed?

segaloco via TUHS tuhs at tuhs.org
Fri May 22 07:01:36 AEST 2026


So I've been playing around with portability testing various bits of software I've written over the years and have run into an interesting scenario.  On all modern UNIX-like platforms I've tried, the following is an example sed script and the result I get anywhere I've used it:

> $ echo beep | sed 's/b\(..\)p/j\1p/g'
> jeep

I use group replacement like this all over the place.  Well, as part of my experiments, I exported "POSIXLY_CORRECT" on one of my GNU setups, and with this set, GNU sed complains:

> sed: warning: using "\(" in the 's' command is not portable

POSIX's section on BRE does list these as grouping operators, and indeed trying this in a V7 emulation it also behaves as expected.  Is there some historic implementation that this grouping does *not* work in when using BREs (as opposed to -E EREs)?  I'm struggling to find where this is documented to cause portability problems, usually my portability check these days is the gaggle of GNU, FreeBSD, macOS, and Solaris with an occasional V7 check when I'm feeling really paranoid...and this checks out on all of those.

For the record, in GNU sed this warning is triggered, when POSIXLY_CORRECT, under any s command where an escaped character other than '&', '\\', '[0-9]', '\n', or the separator character ('/' default) is found.  Testing this, it'll also balk at, for instance, '\?'.

For the record, section 9.3.6 of Base Definitions states:

> A subexpression can be defined within a BRE by enclosing it between the character pairs "\(" and "\)".

Am I missing something obvious here?  Is there some weird but prominent historic sed (and/or BRE implementation) I'm overlooking?  Thanks for any insight, searching for this on the web is proving difficult and fruitless.

- Matt G.


More information about the TUHS mailing list