【问题标题】:Bash substitution cut off end of stringBash 替换切断了字符串的结尾
【发布时间】:2020-06-04 21:49:51
【问题描述】:

我有 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 xxxx.xxxxx@gmail.com
        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 xxxx.xxxxx@gmail.com
        ServerName ooooooooooooooo.com

如您所见,替换切断了字符串的结尾。有人可以告诉我它有什么问题吗?非常感谢。

【问题讨论】:

  • 没有错,它完全可以正常工作。您最好使用sed 替换单独的模板文件,或者使用bash here document 将内联模板的部分替换为变量值..

标签: bash shell substitution


【解决方案1】:

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

试试这个:

(我也将替换设为全局,以便您可以在文件中多次重复使用同一个占位符)

#!/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

【讨论】:

  • 非常感谢。这就是问题所在。我将其替换为 placeholder
猜你喜欢
  • 1970-01-01
  • 2013-09-28
  • 2017-08-02
  • 1970-01-01
  • 2013-08-30
  • 1970-01-01
  • 1970-01-01
  • 2014-11-30
  • 2015-09-10
相关资源
最近更新 更多