3

I want to replaced all number with '@' symbol. I am using the below sed command , but not getting the desired result.

command -

echo "abc 434 pankaj 444" | sed 's/[0-9]*/@/g'

Result -

@a@b@c@ @ @p@a@n@k@a@j@ @
  • 1
    echo "abc 434 pankaj 444" | sed 's/[0-9]/@/g' – Ipor Sircer Dec 3 '17 at 16:32
6

Well, quite simply, [0-9]* matches strings that consist entirely of zero or more digits, include empty strings. Anything that matches an empty string, matches between any two characters, so the replacement @ is added between all letters in the input. Strings of multiple digits are replaced with one @ since the expression matches all consecutive digits at once.

So in the input string ab43 the matches to [0-9]+ are (with some whitespace added for clarity):

    a   b   434
  ^   ^     ^^^- here, a string of some digits
  ^   ^- here, a zero-length string
  ^- here, a zero-length string

Use [0-9] to match exactly one digit, or [0-9][0-9]* to match one or more (or [0-9]+ in extended regular expressions).

  • then the regex pattern should replace all alphabets with '@' symbols, since alphabets has zero digits. – Pankaj Pandey Dec 3 '17 at 17:20
  • @PankajPandey, err, right. I rephrased that a bit. – ilkkachu Dec 3 '17 at 17:26
  • @PankajPandey, should they be? Neither [0-9]* nor [0-9] match any letters, and I thought you wanted to replace only numbers? – ilkkachu Dec 3 '17 at 17:37
  • by that logic, alphabetic characters should also be replaced by '@' since they also do not match to any of the digits. – Pankaj Pandey Dec 3 '17 at 17:38
  • i just want to understand the behaviour of sed command, as I feel it's behaviour is somewhat erratic. – Pankaj Pandey Dec 3 '17 at 17:38
-1

You can achieve this by awk command too


echo "abc 434 pankaj 444" |awk '{gsub("[0-9]","@",$0);print $0}'

  • 1
    While true, sed is the right tool for the job and will work given a small modification. – Mark Perryman Dec 3 '17 at 18:24

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.