89

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'
melpomene
  • 84,125
  • 8
  • 85
  • 148
user2036880
  • 1,463
  • 2
  • 11
  • 9
  • 1
    @tchrist when did i mention that i use perl – user2036880 Feb 03 '13 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? – Mike H-R May 28 '14 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." – Robin A. Meade Apr 03 '21 at 04:35
  • 2
    @RobinA.Meade Agreed. Whoever voted to close the question hasn’t understood it properly. – Manngo Sep 01 '22 at 07:13

3 Answers3

70

\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
saulotoledo
  • 1,737
  • 3
  • 19
  • 36
Kamil
  • 2,712
  • 32
  • 39
  • 27
    but then why `\w` works – user2036880 Feb 03 '13 at 10:26
  • 8
    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 http://www.gnu.org/software/sed/manual/sed.html – Kamil Feb 03 '13 at 10:31
  • 1
    @user2036880 as I indicate in the second part of my answer `\d` has different meaning in sed. – Ivaylo Strandjev Feb 03 '13 at 10:43
  • accepted, +30 and no one is missing \ before + – papo Nov 10 '18 at 05:18
  • Backslash is not needed before a quantified in this regex. – Kamil Nov 10 '18 at 22:07
37

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.

Community
  • 1
  • 1
Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
-9

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.

Fan Yer
  • 377
  • 3
  • 7