Currently, I have files which contain sections like this:
code statement1
code statement2
# BEGIN SOMENAME
some code
some other code
# END SOMENAME
code statement n +1
code statement n +1
What I want to do is to comment out what is between
# BEGIN SOMENAME
and
# END
so that in the end, it looks like this:
code statement1
code statement2
# BEGIN SOMENAME
# some code
# some other code
# END SOMENAME
code statement n +1
code statement n +1
Can I achieve this with awk
or sed
? And can I reverse it easily with an operation that "comments in" again?
What I want to avoid is making mistakes, so if the lines are already commented out
they should be left alone. Also, in "comment in", it should not try to do something if the lines between the end and begin do not start with a #
.
Found a possible solution:
awk '
BEGIN {
i=0;
line_with_no_comment_found=0
}
/^# END/ {
m=0;
if ( line_with_no_comment_found == 1 ) {
for (var in a) print "# "a[var]
} else {
for (var in a) print a[var]
}
delete a;
i=0;
line_with_no_comment_found=0;
}
/^# / {
if (m==0) {
print
} else {
a[i++]=$0;
}
}
!/^# / {
if (m==0) {
print
} else {
a[i++]=$0;
line_with_no_comment_found=1
}
}
/^# BEGIN ([a-zA-Z_])([1-9][0-9]*)*/ {
m=1;
}
END { }
'<<EOF