Home > Enterprise >  How to comment out multiple lines based on specific grep?
How to comment out multiple lines based on specific grep?

Time:09-20

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?

CodePudding user response:

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

CodePudding user response:

I think I figured out a solution with awk

awk '/^case\ \$\-\ in/{f=1} !NF{f=0} f{$0="#" $0} 1'  /home/mruser/myfile > /home/mruser/.myfile_awk && mv -f /home/mruser/.myfile_awk /home/mruser/myfile
  • use awk and match on case $- in
  • comment out that line.
  • comment out all lines after that line up to first blank line. Do not comment out the blank line
  • send output to a temp file called .myfile_awk
  • move the temp file to the other files place

This seems to work, albite a bit hacky. If anyone else has a better alternative please share.

  • Related