How to UNCOMMENT a line that contains a specific string using Sed?

user3864928 picture user3864928 · Jul 22, 2014 · Viewed 56k times · Source

The lines in the file :

-A INPUT -m state --state NEW -m tcp -p tcp --dport 2000 -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 2001 -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 2002 -j ACCEPT

to comment out let's say the line that contains

2001

i can simply run this SED command:

sed -i '/ 2001 /s/^/#/' file

but now how do i revert back ?

as in uncomment that same line ?

i tried

sed -i '/ 2001 /s/^//' file

that does not work.

Answer

JNLK picture JNLK · Dec 8, 2014

Yes, to comment line containing specific string with sed, simply do:

sed -i '/<pattern>/s/^/#/g' file

And to uncomment it:

sed -i '/<pattern>/s/^#//g' file

In your case:

sed -i '/2001/s/^/#/g' file    (to comment out)
sed -i '/2001/s/^#//g' file    (to uncomment)

Option "g" at the end means global change. If you want to change only a single instance of pattern, just skip this.