0
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
}

This function working fine for non escape character but when escape character available then it fail..

So We can build function, for escap character ?

1

You can do it like this:

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"
}

The delimiters \Q...\E in Perl regular expressions ensure that anything between them is interpreted as a literal string rather than a regular expression (see perldoc perlre).

Note that the substitution can be carried out in one step only and the file name should be quoted (as in "$InputFile") to avoid word splitting. This applies whether you use sed or perl.

| improve this answer | |
0

I have Checked sed with -E agrs but not work, so I used following changes, seems working..

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
}

Test

root@router:~# bash -x /tmp/test.sh
+ CommentAppend 'connection = sqlite:////var/lib/keystone/keystone.db' 'connection = mysql://keystoneUser:keystonePass@10.10.10.51/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:keystonePass@10.10.10.51/keystone'
+ local 'append=connection = mysql:\/\/keystoneUser:keystonePass@10.10.10.51\/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:keystonePass@10.10.10.51\/keystone/' /tmp/test.conf
| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.