103

I am trying to use \d in regex in sed but it doesn't work:

sed -re 's/\d+//g' 

But this is working:

sed -re 's/[0-9]+//g' 
5
  • 1
    @tchrist when did i mention that i use perl Commented Feb 3, 2013 at 14:16
  • 1
    @tchrist I think you mean perl -pe 's/\d+//g' or rather that's what I need to use to get it to print out a file (so using it in the form: perl -pe 's/\d+//g' example.txt > example2.txt ) were you suggesting a different usage? Commented May 28, 2014 at 12:51
  • 1
    This question shouldn't have been closed. It is focused on why \d doesn't represent a digit in sed. The question referenced as a duplicate is about "How to extract text from a string using sed." Commented Apr 3, 2021 at 4:35
  • 2
    @RobinA.Meade Agreed. Whoever voted to close the question hasn’t understood it properly. Commented Sep 1, 2022 at 7:13
  • See also stackoverflow.com/questions/18514135/… Commented Apr 5, 2024 at 9:28

3 Answers 3

79

\d is a switch not a regular expression macro. If you want to use some predefined "constant" instead of [0-9] expression just try run this code:

s/[[:digit:]]+//g 
Sign up to request clarification or add additional context in comments.

7 Comments

but then why \w works
As it's written is sed documentation "\w Matches any “word” character. A “word” character is any letter or digit or the underscore character." And there's another interesting line "In addition, this version of sed supports several escape characters (some of which are multi-character) to insert non-printable characters in scripts (\a, \c, \d, \o, \r, \t, \v, \x). These can cause similar problems with scripts written for other seds." For more look at gnu.org/software/sed/manual/sed.html
@user2036880 as I indicate in the second part of my answer \d has different meaning in sed.
accepted, +30 and no one is missing \ before +
Backslash is not needed before a quantified in this regex.
|
44

There is no such special character group in sed. You will have to use [0-9].

In GNU sed, \d introduces a decimal character code of one to three digits in the range 0-255. As indicated in this comment.

Comments

-12

You'd better use the Extended pattern in sed by adding -E. In basic RegExp, \d and some others won't be detected -E Interpret regular expressions as extended (modern) regular expressions rather than basic regular expressions (BRE's). The re_format(7) manual page fully describes both formats.

1 Comment

\d won't be detected with -E either.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.