Suppose i have a variable $email
whose value is [email protected]
.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\[email protected]
in this case.
Suppose i have a variable $email
whose value is [email protected]
.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\[email protected]
in this case.
sed -E 's/\./\\\./g;s/(.*)\\\./\1\./'
should do it.
Test
$ var="[email protected]"
$ echo $var | sed -E 's/\./\\\./g;s/(.*)\\\./\1./'
stack\[email protected]
$ var="[email protected]."
$ 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="[email protected]"
gawk -F'.' '{OFS="\\.";a=$NF;NF--;print $0"."a}' <<< "$var"
Output:
stack\[email protected]
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' <<<'[email protected]'
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##*.}