The proper way is to make
s work only on lines that match a certain pattern, the substitution can be quite simple then.
This will remove leading
# from lines that contain
sed '/LINE/ s/^#//'
This will remove all leading
sed '/LINE/ s/^#*//'
This will add one
sed '/LINE/ s/^/#/'
Obviously you cannot remove
# that isn't there, but you can add
# while a leading
# is already there. An improvement to the above command that doesn't modify already commented lines:
sed '/^\([^#].*\|\)LINE/ s/^/#/'
^ matches the beginning of the line and
[^#] matches a non-
#. It's possible to improve the command further, so
# with leading blanks at the beginning of a line will not be commented out again; I won't do this here.
/regex/ s…. If your regex happens to contain slashes, escape them with
\; or choose another character to embrace the regex, but then you need to escape the opening one (e.g.