How to toggle a comment in a line using sed

Viewed 180

I have a txt file with a line I want to comment, I am using sed

comment out

sed -i 's/line1/#line1/' myfile.ini

uncomment out

sed -i 's/#line1/line1/' myfile.ini

this works but the problem is that sometimes I run this twice by mistake, and I end up with a line like

##line1

so when I run the uncomment command, the line is now

#line1

is there an alternative to toggle the comment? this is inside a bash script so I am happy to add a few lines if necessary.

thanks

2 Answers

You can use this sed command:

sed -i 's/^[[:blank:]]*line1/#&/' myfile.ini

Here matching pattern is ^[[:blank:]]*line1 which means match start of line followed by 0 or more whitespace characters before matching line1. And replacement is #& to place # before matched string.

Similarly for uncommenting use:

sed -Ei 's/^#([[:blank:]]*line1)/\1/' myfile.ini

Which matches # at line start followed by 0 or more whitespaces before matching line1. It capture part after # in capture group #1 and uses back-reference \1 in replacement to remove just the # part.

Building Upon @Anubhava's Answer,
You can combine the two into a One-Liner to Toggle comments with:

sed -Ei 's/^[[:blank:]]*line1/#&/;t;s/^#([[:blank:]]*line1)/\1/' myfile.ini

This is a simple "if-else" statement in sed. More About Sed Branching & Flow Control Here

Related