Issue
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
Solution
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.
Answered By - anubhava Answer Checked By - Cary Denson (WPSolving Admin)