Take the 2-minute tour ×
Ask Different is a question and answer site for power users of Apple hardware and software. It's 100% free, no registration required.

It looks like sed that comes with Mac OS 1.7.4 is the original one, without the + metacharacter. Can I get the + metacharacter functionality?

share|improve this question

2 Answers 2

up vote 1 down vote accepted

The + is a GNU extension of sed that matches one or more of the preceding expression but the version on OS X is BSD sed. A version of GNU sed has been ported to OS X on MacPorts. Otherwise you'll need to try a workaround.

For example, to match one or more digits, you could use [0-9][0-9]* instead of [0-9]+

share|improve this answer
    
You can also use curly brackets in basic regular expressions, but they have to be backslash-escaped: echo $'aaa\na\nb' | sed -n '/a\{1,\}/p' –  ؘؘؘؘ Jul 20 '12 at 18:25

OS X's implementation of sed uses the "basic" regular expression format by default, which doesn't support +. From man re_format:

Obsolete (``basic'') regular expressions differ in several respects.  `|'
is an ordinary character and there is no equivalent for its functional-
ity.  `+' and `?' are ordinary characters, and their functionality can be
expressed using bounds (`{1,}' or `{0,1}' respectively).  Also note that
`x+' in modern REs is equivalent to `xx*'.  The delimiters for bounds are
`\{' and `\}', with `{' and `}' by themselves ordinary characters.  The
parentheses for nested subexpressions are `\(' and `\)', with `(' and `)'
by themselves ordinary characters. [...]

So, what can you do? Well, one possibility is to tell sed to use the modern format with the -E switch. This may, however, force you to rewrite other parts of your RE to conform (for example, swapping \( ... \) with ( ... )). Another option is to use one of the suggested alternate forms above. Here are examples using the various approaches to match "A" followed by one or more "B" or "C", followed by "D":

sed -E 's/A[BC]+D/[match]/'
sed 's/A[BC]\{1,\}D/[match]/'
sed 's/A[BC][BC]*D/[match]/'
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.