Search code examples
bashawksedgrepcomments

How to comment out multiple lines based on specific grep?


Here is a test file

dog
dogcatmoose
case $- in 
      *i*);;
        *) return;;
esac

catmoose
case
esac
dog cat
esac

I need to comment out the following:

dog
dogcatmoose
#case $- in 
#      *i*);;
#        *) return;;
#esac

catmoose
case
esac
dog cat
esac

Notice that ONLY the specific lines were commented out. Note also I need to do this to multiple files and those lines commented out maybe located on different areas of the file. However those lines will always be together. Therefore I cannot comment out with sed based on line numbers.

How can I comment out those lines specifically, which will work on multiple files where that section maybe anywhere in the file. I assume I can grep on 'case $- in' then comment out that line and all lines UP to the first esac instance after 'case $- in'.

How can I accomplish this?


Solution

  • If I understand the problem correctly, then you could use a sed range address to comment out that region:

    $ sed '/case $- in/,/esac/ s/^/# /' <<\TEXT
    dog
    dogcatmoose
    case $- in
          *i*);;
            *) return;;
    esac
    
    catmoose
    case
    esac
    dog cat
    esac
    TEXT
    

    Output:

    dog
    dogcatmoose
    # case $- in
    #       *i*);;
    #         *) return;;
    # esac
    
    catmoose
    case
    esac
    dog cat
    esac
    

    And, of course, you can do it in-place:

    $ sed -i.back '/case $- in/,/esac/ s/^/# /' target.sh
    $
    $ tail target.sh target.sh.back 
    ==> target.sh <==
    # case $- in
    #       *i*);;
    #         *) return;;
    # esac
    
    catmoose
    case
    esac
    dog cat
    esac
    
    ==> target.sh.back <==
    case $- in
          *i*);;
            *) return;;
    esac
    
    catmoose
    case
    esac
    dog cat
    esac