Bash替换字符串的结尾

问题描述 投票:0回答:1

我有bash脚本,应通过用户输入替换文本模板中的某些占位符。

#!/bin/bash
# Run this script as bash command like: bash create-apache-site.sh

read -p 'Write url without www and http prefixes: ' url

template=$(</etc/apache2/sites-available/000-default.conf)
template2=("${template/1*****/$url}")

echo "$template2" > /home/Camo/template.txt

模板文件是带有占位符(1 *****,2 *****,...)的多行字符串,看起来像]

<VirtualHost *:80>
        ServerAdmin [email protected]
        ServerName 1*****

        ErrorLog ${APACHE_LOG_DIR}/www/2*****/error.log
        CustomLog ${APACHE_LOG_DIR}/www/3*****/access.log combined

        DocumentRoot /var/www/html/4*****
        <Directory /var/www/html/5*****/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride All
                Order allow,deny
                allow from all
                Require all granted
        </Directory>
        RewriteEngine on
        RewriteCond %{SERVER_NAME} = 6*****
        RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

但是此脚本的结果是此损坏的文件

<VirtualHost *:80>
        ServerAdmin [email protected]
        ServerName ooooooooooooooo.com

如您所见,替换会截断字符串的结尾。有人可以告诉我这是怎么回事吗?非常感谢。

bash shell substitution
1个回答
0
投票

您必须先逃脱*才能进行替换。也许更好的方法是不使用*作为占位符?但我留给你。

尝试一下(我也将替换项设置为全局):

#!/bin/bash
# Run this script as bash command like: bash create-apache-site.sh

read -p 'Write url without www and http prefixes: ' url

template=$(</etc/apache2/sites-available/000-default.conf)
template2=("${template//1\*\*\*\*\*/$url}")

echo "$template2" > /home/Camo/template.txt
© www.soinside.com 2019 - 2024. All rights reserved.