tags:

views:

129

answers:

3

Note:

  • Bash 3.00

How to substitute this example string 123456789, to look like 123-456-789

#!/bin/sh
# trivial example
read number;
# monotically substitute '-' into string after first three and dix digits
+7  A: 
phone=`echo $phone | sed 's/\(...\)\(...\)/\1-\2-/'`
Marcelo Cantos
Thank you Marcelo. Where can I learn more about this?
Aaron
$ man sedSed is a simple text filtering program that takes input from stdin or a file and applies ed commands to it. It's short for *streaming ed*. The backquotes execute the contained command and substitute its output on the command-line (`man bash` and search for `backquote` for more info on this).
Marcelo Cantos
`$()` is preferred over backquotes and works in Bash, zsh, ksh and dash (sh), but may not in the Bourne shell and doesn't in the C shell. It is specified by POSIX. http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_03
Dennis Williamson
A: 

one way with gawk

$ echo "123456789" |awk  'BEGIN{FS=""}{ for(i=1;i<=NF;i+=3)s=s$(i)$(i+1)$(i+2)"-";sub(/-$/,"",s);print s } '
123-456-789

$ echo "123456789abcdef" | awk  'BEGIN{FS=""}{ for(i=1;i<=NF;i+=3)s=s$(i)$(i+1)$(i+2)"-";sub(/-$/,"",s);print s } '
123-456-789-abc-def
ghostdog74
+8  A: 

Without the use of sed:

$ number=123456789
$ number=${number:0:3}-${number:3:3}-${number:6:3}
$ echo $number
123-456-789
Dennis Williamson