Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape plus sign on mac os x (BSD) sed?

I'm trying to find and replace one or more occurrences of a character using sed on a mac, sed from the BSD General Commands.

I try:

echo "foobar" | sed -e "s/o+//g

expecting to see:

fbar

But instead I see

foobar

I can of course just expand the plus manually with:

echo "foobar" | sed -e "s/oo*//g"

but what do I have to do to get the plus sign working?

like image 394
Alec Jacobson Avatar asked Dec 15 '10 19:12

Alec Jacobson


People also ask

What are special characters for sed?

The special character in sed are the same as those in grep, with one key difference: the forward slash / is a special character in sed. The reason for this will become very clear when studying sed commands.


1 Answers

Using the /g flag, s/o//g is enough to replace all o occurrences.

Why + doesn't work as expected: in old, obsolete re + is an ordinary character (as well as |, ?). You should specify -E flag to sed to make it using modern regular expressions:

echo "foobar" | sed -E -e "s/o+//"
# fbar

Source: man 7 re_format.

like image 107
khachik Avatar answered Oct 25 '22 11:10

khachik