while循环插入sed

时间:2017-05-17 21:14:03

标签: bash sed while-loop scripting

我试图在第二次出现的字符串中向配置文件中添加多行。我可以让我的While循环将代码附加到文件的末尾,但它需要插入某行以下的另一行

<$site_conf tr '\n' '\0' |
sed -e "s/.*/$(yes '\0' | head -n 1 | tr -d '\n')/g" |
tr '\0' '\n' >> $site_conf
sed -i '0,/*:80/! {0,/*:80/ s/*:80/*:443/}' $site_conf
TEMPLATE='SSLEngine.txt'
while read LINE; do
    echo $LINE |
    sed 's/${SSLplaceholder}/'${SSLdomain}'/' >> $site_conf
done < $TEMPLATE;;

这会生成如下配置文件:

<VirtualHost *:80>
ServerName mysite.preview.something.com
DocumentRoot /home/mysite/web/content

<Directory /home/mysite/web/content>
Options +FollowSymLinks -Indexes
AllowOverride All
Require all granted
</Directory>

LogLevel warn
ErrorLog /home/mysite/web/log/mysite-error.log
CustomLog /home/mysite/web/log/mysite-access.log combined
</VirtualHost>
<VirtualHost *:443>
ServerName mysite.preview.something.com
DocumentRoot /home/mysite/web/content
<Directory /home/mysite/web/content>
Options +FollowSymLinks -Indexes
AllowOverride All
Require all granted
</Directory>

LogLevel warn
ErrorLog /home/mysite/web/log/mysite-error.log
CustomLog /home/mysite/web/log/mysite-access.log combined
</VirtualHost>
SSLEngine on
SSLProtocol all -SSLv2
SSLCipherSuite HIGH:MEDIUM:!aNULL:!MD5
SSLCertificateFile /etc/apache2/ssl/domain.com.crt
SSLCertificateKeyFile /etc/apache2/ssl/private/domain.com.key
SSLCertificateChainFile /etc/apache2/ssl/int.crt

我希望最后6行插入第二行ServerName行之前和DocumentRoot行之前。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

如果六个行在名称在变量TEMPLATE中的文件中(如果我正确处理变量),这是一个sed命令,它将执行此操作:

sed '/DocumentRoot/,/ServerName/ {
/ServerName/r '"${TEMPLATE}"'
}'

答案 1 :(得分:0)

好的 - 这里终于满足了我的所有要求:

    ssltemplate="ssltemplate.txt"
    <$site_conf tr '\n' '\0' |
    sed -e "s/.*/$(yes '\0' | head -n 1 | tr -d '\n')/g" |
        tr '\0' '\n' >> $site_conf
    sed -i '0,/*:80/! {0,/*:80/ s/*:80/*:443/}' $site_conf
    TEMPLATE='SSLEngine.txt'
    while read LINE; do
        echo $LINE |
        sed 's/${SSLplaceholder}/'${SSLdomain}'/' >> $ssltemplate
    done < $TEMPLATE
    sed -i '1,/ServerName/{p;d}; /ServerName/,$ {1,1 r ssltemplate.txt
    }' $site_conf
    rm -r ssltemplate.txt