SED/tr etc.. : How to comment out a line that contains "string" in a file?
Asked Answered
S

2

4

my file contains lines such as these:

-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

i want to comment out ( add # infront of ) the line that is

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

how can i do this via SED or some other method via command line ?

should i seek for .. e.g..

2001

and then comment out that whole line ( add # infront of )

or should i search for the entire line and then replace it with a new one that contains # ?

what would be the most practical method ? ( fastest )

Swath answered 22/7, 2014 at 9:37 Comment(0)
S
15

Through sed,

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

Add inline edit -i option to save the changes made.

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

Example:

$ sed '/ 2001 /s/^/#/' 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
Smear answered 22/7, 2014 at 9:39 Comment(0)
A
3

This awk would do too.

awk '/2001/ {$0="#"$0}1' 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
Atlanta answered 22/7, 2014 at 10:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.