带有自动转义字符的 sed

带有自动转义字符的 sed
CommentAppend() {
    # Comment line and append line below commented line 
    local comment="$1"      # search this line and comment it 
    local append="$2"       # Append this line below commented line 
    local InputFile="$3"    

    sed -i "s/${comment}/#${comment}/g ; s/#${comment}/& \n${append}/" $InputFile
}

此函数对于非转义字符工作正常,但是当转义字符可用时,它会失败。

那么我们可以为转义字符构建函数吗?

答案1

你可以这样做:

CommentAppend() {
    # Comment line and append line below commented line 
    local comment="$1"      # search this line and comment it 
    local append="$2"       # Append this line below commented line 
    local InputFile="$3"    

    perl -pi -e "s/\Q${comment}\E/#${comment}\n${append}/g" "$InputFile"
}

Perl 正则表达式中的分隔符\Q...\E确保它们之间的任何内容都被解释为文字字符串而不是正则表达式(请参阅 参考资料perldoc perlre)。

请注意,替换只能一步完成,并且应将文件名加引号(如 中"$InputFile")以避免分词。无论您使用sed或,这都适用perl

答案2

我已经用-Eagrs 检查了 sed 但不起作用,所以我使用了以下更改,似乎有效。

CommentAppend() {
        # Comment line and append line below commented line
        local comment="$( echo "$1" | sed 's/\(\/\)/\\\//g' )"  # search this line and comment it
        local append="$( echo "$2" | sed 's/\(\/\)/\\\//g' )"   # Append this line below commented line
        local InputFile="$3"


        sed -i "s/${comment}/#${comment}/g ; s/#${comment}/& \n${append}/" $InputFile
}

测试

root@router:~# bash -x /tmp/test.sh
+ CommentAppend 'connection = sqlite:////var/lib/keystone/keystone.db' 'connection = mysql://keystoneUser:[email protected]/keystone' /tmp/test.conf
++ sed 's/\(\/\)/\\\//g'
++ echo 'connection = sqlite:////var/lib/keystone/keystone.db'
+ local 'comment=connection = sqlite:\/\/\/\/var\/lib\/keystone\/keystone.db'
++ sed 's/\(\/\)/\\\//g'
++ echo 'connection = mysql://keystoneUser:[email protected]/keystone'
+ local 'append=connection = mysql:\/\/keystoneUser:[email protected]\/keystone'
+ local InputFile=/tmp/test.conf
+ sed -i 's/connection = sqlite:\/\/\/\/var\/lib\/keystone\/keystone.db/#connection = sqlite:\/\/\/\/var\/lib\/keystone\/keystone.db/g ; s/#connection = sqlite:\/\/\/\/var\/lib\/keystone\/keystone.db/& \nconnection = mysql:\/\/keystoneUser:[email protected]\/keystone/' /tmp/test.conf

相关内容