开发者

Replace text in file with user input containing space, using sed

开发者 https://www.devze.com 2023-03-27 12:24 出处:网络
My script: #!/bin/sh cp -f host.tpl host.conf mkdir -p /var/www/$1 server_replace=\"s,{server_name},$1,g\"

My script:

#!/bin/sh

cp -f host.tpl host.conf
mkdir -p /var/www/$1

server_replace="s,{server_name},$1,g"
sed -i $server_replace host.conf

alias_replace="s,{server_alias},$2,g"
sed -i $alias_replace host.conf

File in which i'm doing replacemants (vhost.tpl):

<VirtualHost 0.0.0.0:80>
    ServerName {server_name}
    ServerAlias {server_alias}
    DocumentRoot /var/www/{server_name}
</VirtualHost>

It works fine when I'm creating vhost with one 开发者_StackOverflow社区server alias

./vhost.sh domain.com www.domain.com

But when I want to have more aliases

./vhost.sh domain.com "www.domain.com m.domain.com"

script fails with message like

sed: -e expression #1, char 31: unterminated `s' command

Do I have to escape space character in some way to use it in replacement string?


Just put a pair of double quotes around the $alias_replace reference:

sed -i.bkp "$alias_replace" host.conf

It should do the trick. You just need to do it in the second sed call but I would strongly suggest you tho quote both variables.


sed -i -e "s,{server_name},$1,g" -e "s,{server_alias},$2,g" host.conf

No need for two commands. Every need to use the double quotes.

You could avoid the -e options if you wanted to; I find them clearer than the alternative.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号