sed -E 's/([0-9]{3})-([0-9]{2})-([0-9]{4})/ /g' a.dat > b.dat

This is replacing 111-11-1111 to spaces , but its also replacing 0111-11-1111 to spaces to... But I want it to ignore 0111-11-1111 (basically if there is 4 numeric characters instead of 3)

  • 1
    Could you provide some sample data? Feb 28 '20 at 14:58
  • 2
    It's always trivial to write a regexp to match the strings you want it to match (e.g. .* matches any string) but much harder to write one that doesn't match strings you don't want to match. Without seeing the strings you want to match in context with other strings you don't want to match, we'd just be guessing at how to help you. Which version of sed are you using?
    – Ed Morton
    Feb 28 '20 at 15:01
  • You can append a space in front of the pattern to ensure that only the string with the pattern you need is replaced. eg: sed -E 's/ ([0-9]{3})-([0-9]{2})-([0-9]{4})/ /g' a.dat > b.dat This will work given that the numbers 111-11-1111 appear as individual words.
    – mkc
    Feb 28 '20 at 15:02
  • 1
    Don't you have the file a.dat? We are asking that you post a representative part of that file, edit the question if you have, don't add it in the comments. Feb 28 '20 at 15:17
  • 1
    Both your examples of 544-696-4560 and 0345-678-6547 have three digits in the middle, but your regex has ...{3}-...{2}-...{4}. Is it three or two? Yes, provide an example file, please.
    – ImHere
    Feb 28 '20 at 15:20

You need additional anchors.

  1. Start and end of line (if each entry is in a line)

    sed -E 's/^[0-9]{3}-[0-9]{2}-[0-9]{4}$/ /g' file
  2. Or word boundaries (space-text transitions) (GNU sed):

    sed -E 's/\<[0-9]{3}-[0-9]{2}-[0-9]{4}\>/ /g' file
  3. Or capture (and return) an optional additional character. But this require that all matched strings are surrounded by additional characters.

    sed -E 's/([^0-9])[0-9]{3}-[0-9]{2}-[0-9]{4}([^0-9])/\1 \2/g' file
  4. Or (not in sed) use PCRE that allow lookahead and lookbehind.

    perl -pe '$_ =~ s/(?<!\d)\d{3}-\d{2}-\d{4}(?!\d)/ /g' file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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