19

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?

1
  • 1
    using /g flag, s/o//g is enough to replace all o occurrences.
    – khachik
    Dec 15, 2010 at 19:09

4 Answers 4

35

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.

1
  • +1, with the -E flag it works as described. For some reason I couldn’t find that in the man/info pages, though. Officially it appears that the -r and --regexp-extended options are the way to go.
    – Chriki
    Mar 21, 2014 at 8:08
1

Sed is sad for regexes. You could either try the -E, which might work with BSD, or you could try this one instead:

sed -e "s/o\{1,\}/"

Perhaps there are too many sed's out there to have a usable tool on any system.

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

worked for me on Mac OS X 10.6.

I remembered that I replaced my BSD version of sed with GNU sed 4.2, so this may or may not work for you.

2
  • In Terminal.app you may need to use a double backslash. Dec 15, 2010 at 19:09
  • @eyelidlessness Doesn't work either. See my answer for more info.
    – khachik
    Dec 15, 2010 at 19:16
0

You can use this, on linux or unix.

echo "foobar" | perl -pe "s/o+//g"
2
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient reputation you will be able to comment on any post. Aug 14, 2015 at 9:49
  • Use this can solve the problem, and don't need care about the escape issue.
    – XY WANG
    Aug 14, 2015 at 10:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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