Just a brief comment about the updated sed
command in your question, which currently reads
sed -i 's/^[a-zA-Z0-9-_]*$@^[a-zA-Z0-9-_]*$.^[a-z]*$/"${new_email_address}"/g' FILE
Notice that this contains two invalid character ranges (both read 0-9-_
) and that the variable new_email_address
would not be expanded by the shell as it is in a single-quoted string. I'm also not sure about what the intention is with $@^
and $.^
, as the $
and ^
would be matching those characters literally at those positions in the expression.
Not seeing how the $to
variable is used in the rest of the file, I'm going to assume that it's only assigned to in one single place, and that the line that you show occurs exactly like it does in the file.
sed 's/$to = ".*";$/$to = "'"$new_email_address"'";/' file >file.new
There is no point in trying to match an email address since we know already that the $to
variable holds an email address. The only thing we need to worry about is trying to find the correct line. Matching email addresses with regular expressions is notoriously difficult.
A few things to note here:
- The
$
in $to
does not need special handling as it's not occurring last in the expression. If you use -E
to enable extended regular expressions, then firstly, don't, and secondly, escape the $
in $to
as \$
in the pattern.
- The string
$to
will not be seen as a shell variable as it's within single quotes.
$new_email_address
is a shell variable, so we're temporarily breaking out of the single quotes to introduce the value of that variable, double quoted.
I would suggest not using -i
here, as you don't yet know whether the substitution does the right thing or whether it messes up the file. It's better to write the result to a fresh filename instead.
Also, with -ir
, you are instructing sed
to use r
as the backup file suffix. I assume that you wanted to use the option -r
(or -E
, which would be more commonly supported). However, neither -r
nor -E
is needed as we're not using any extended regular expressions for this simple substitution.
Testing the above command:
$ cat file
$to = "example-1_2@example-1_2.com";
$ new_email_address=myself@my.host.here.net
$ sed 's/$to = ".*";$/$to = "'"$new_email_address"'";/' file >file.new
$ cat file.new
$to = "myself@my.host.here.net";
example-1_2@example-1_2.com
in each occurrence (normally it would occur just once but I it might occur twice or more by some rare copying mistake).sed "s/example-1_2@example-1_2.com/${new_email_address}/"
?