-2

Hi I'm running the line:

sudo sed -i "s/${SERVER_ENVIRONMENT}/$SERVER_ENVIRONMENT/" /etc/nginx/sites-available/default.conf

in a bash script.

I want to replace the string ${SERVER_ENVIRONMENT} with the value of the environment variable "$SERVER_ENVIRONMENT", which is stored in /etc/environment, but when I run the bash script I'm getting this error:

sed: -e expression #1, char 0: no previous regular expression

Does anyone know how I fix this error? Cheers

edpo1996
  • 39
  • 5

1 Answers1

0

sed doesn't understand literal strings, only regexps and backslash-enabled replacement text, see is-it-possible-to-escape-regex-metacharacters-reliably-with-sed for details.

I'd use awk for this since it does let you use literal strings:

awk -i inplace '
    BEGIN { old="${SERVER_ENVIRONMENT}"; new=ENVIRON["SERVER_ENVIRONMENT"] }
    s=index($0,old) { $0=substr($0,1,s-1) new substr($0,s+length(old)) }
1' /etc/nginx/sites-available/default.conf

the above will work no matter which characters $SERVER_ENVIRONMENT contains.

To do "inplace" editing it's using awk -i inplace '...' file with GNU awk just like you can do sed -i '...' file with GNU sed.

Since your variable name is all-upper-case I assume it's exported (see correct-bash-and-shell-script-variable-capitalization for why I say that) but if not then set it to itself on the command line so you don't have to export it for it to be available in ENVIRON[]:

SERVER_ENVIRONMENT="$SERVER_ENVIRONMENT" awk -i inplace '...' file
Ed Morton
  • 188,023
  • 17
  • 78
  • 185