Aaron
Aaron

Reputation: 2863

How to substitute a string in bash script

Note:

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 

Upvotes: 1

Views: 1012

Answers (3)

Dennis Williamson
Dennis Williamson

Reputation: 359865

Without the use of sed:

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

Upvotes: 9

ghostdog74
ghostdog74

Reputation: 342263

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

Upvotes: -1

Marcelo Cantos
Marcelo Cantos

Reputation: 185852

phone=`echo $phone | sed 's/\(...\)\(...\)/\1-\2-/'`

Upvotes: 6

Related Questions