Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I've been fiddling with this for a while now and can't seem to figure it out. What I'm trying to do is replace all numbers in a file with a single #.

Sounds simple, and it should be, but I can't get my head around it. Any help would be appreciated.

What I've got so far (but doesn't work) is:

echo "fdsafdsa 32432 dsafdas" | sed 's/[0-9]+/#/g'

The output I expect is:

fdsafdsa # dsafdas

But sed gives me the same string with nothing replaced.

Any clues?

share|improve this question
up vote 6 down vote accepted

You don't need the +. Just use the following:

echo "fdsafdsa 32432 dsafdas" | sed 's/[0-9]/#/g'

[0-9] will already match all digits, and replace every single one with #.

Since + is extended syntax, you could also do:

echo "fdsafdsa 32432 dsafdas" | sed -E 's/[0-9]+/#/g'

to replace the whole block of digits with one #.

share|improve this answer
Thanks! It was indeed the extended syntax I was looking for. – acidtv May 2 '12 at 9:18
Without extended syntax, you could have also escaped the +, e.g. sed 's/[0-9]\+/#/g', since otherwise it'll be treated as a literal plus sign. – slhck May 2 '12 at 9:19
I actually tried that and it didn't work when I tried it. Looking back now it appears that on my mac sed \+ doesn't work, but it debian it does. I learned alot today :) – acidtv May 2 '12 at 9:22
The interpretation is different on GNU sed (the one shipped with Debian) and BSD sed (the one in OS X). It's always good to examine the manpage of both utilities before, since GNU and BSD tools can differ in functionality. – slhck May 2 '12 at 9:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .