Suppose i have a variable $email
whose value is stack.over@gmail.com
.I want to add a \
before every dot except the last dot and store it in a new variable $email_soa
.
$email_soa
should be stack\.over@gmail.com
in this case.
Suppose i have a variable $email
whose value is stack.over@gmail.com
.I want to add a \
before every dot except the last dot and store it in a new variable $email_soa
.
$email_soa
should be stack\.over@gmail.com
in this case.
sed -E 's/\./\\\./g;s/(.*)\\\./\1\./'
should do it.
Test
$ var="stack.over@flow.com"
$ echo $var | sed -E 's/\./\\\./g;s/(.*)\\\./\1./'
stack\.over@flow.com
$ var="stack.over@flow.com."
$ echo $var | sed -E 's/\./\\\./g;s/(.*)\\\./\1./'
stack\.over@flow\.com.
Note
The \\
makes a literal backslash and \.
makes a literal dot
You can use gawk
:
var="stack.over@gmail.com"
gawk -F'.' '{OFS="\\.";a=$NF;NF--;print $0"."a}' <<< "$var"
Output:
stack\.over@gmail.com
Explanation:
-F'.'
splits the string by dotsOFS="\\."
sets the output field separator to \.
a=$NF
saves the portion after the last dot in a variable 'a'. NF
is the number of fields.NF--
decrements the field count which would effectively remove the last field. This also tells awk
to reassemble the record using the OFS
This feature does at least work with GNU's gawk
.print $0"."a
prints the reassmbled record along with a dot and the value of a
You could use perl to do this:
perl -pe 's/\.(?=.*\.)/\\./g' <<<'stack.over@gmail.com'
Add a slash before any dots that have a dot somewhere after them in the string.
How about this:
temp=${email%.*}
email_soa=${temp/./\\.}.${email##*.}