0

like say i have a string of numbers that constitute a phone number and are like so

##########

and i want to format them like :

###-###-####

insert only puts in new lines, and i dont know how to make say an expression like

sed (s/[0-9]/TheNumberIFound-/)//3//6

so is there some way i can ask sed to just add something after a matched pattern, or to replace the matched pattern with itself plus some other char?

1 Answer 1

1
$ echo "1234567890" | sed -re 's/([0-9]{3})([0-9]{3})([0-9]{4})/\1-\2-\3/g'
123-456-7890
  • [0-9] does match any digit in one position in the phone number.
  • {3} tells sed to match the pattern prepended to this, 3 times.
  • The ( and ) (parentheses) surrounding the three repeats of these logs the matched numbers in "memories"
    the "memories" are then "recalled" with \1 for the first parenthese, \2 for the second and so on.
  • Therefore \1-\2-\3 makes your reformatted phone number.
  • Add the g at the end to make sed do this more than once per line.

Intentionally attempted to keep language at 'noob' level ;-p

5
  • while yes this does work, i can't get it to work when it's in a script. without the single quotes it doesnt work properly, with them i get an error.
    – arly803
    Oct 17, 2014 at 20:42
  • Doublequotes " should also work. Without quotes you will have the command shell (e.g. bash) attempting to interpret your typing. " allows the shell to substitute $variable or ${variable} for you - but note that sed uses $ for matching end-of-line; which may become a problem.
    – Hannu
    Oct 18, 2014 at 12:00
  • it wasn't the quotes that were at fault, when in my script it wasn't running with them with an error of unknown command"'"(or, when i used double quotes as suggested """) but rather, it was that neither in your answer, nor in my script did we escape the curly braces (even though i did this when i tested the command on an echo just to make sure it worked, just mustn't have registered in my mind). all's good now. thanks for your help.
    – arly803
    Oct 18, 2014 at 12:28
  • -r is there to eliminate the need for the extensive \'s.
    – Hannu
    Oct 18, 2014 at 12:31
  • sed was disallowing me from using any other options after i used the -f option, as it was attempting to interpret them as commands
    – arly803
    Oct 18, 2014 at 14:43

You must log in to answer this question.

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