Smith Dwayne Smith Dwayne - 1 year ago 50
Bash Question

Using sed command in shell script

This is my simple shell script

echo "Enter Web Url:"
read weburl
echo "sed 's/^\(ServerName\)$/\1 "$weburl"/' "$CONFLOC
sed "'s/^\(ServerName\)$/\1 "$weburl"/' "$CONFLOC

When I run this code, I get the result in echo command as following.

sed 's/^\(ServerName\)$/\1' Install/server.conf

But when executing sed command in the next line, It says the below error.

sed: -e expression #1, char 1: unknown command: `''

I tried the command produced in echo statement from Terminal screen, It is working. But
Line number 5
, doesn't working from shell script

Answer Source

You need to use one set of quotes, not two, and since you want the $weburl variable expanded, you need to use double quotes:

sed "s/^\(ServerName\)$/\1 $weburl/" "$CONFLOC"

That'll be OK as long as $weburl doesn't contain any slashes. If it does, you need to use a different character than /, such as %, to separate the parts of the substitute command:

sed "s%^\(ServerName\)$%\1 $weburl%" "$CONFLOC"