Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
590 views
in Technique[技术] by (71.8m points)

regex - SED/tr etc.. : How to comment out a line that contains "string" in a file?

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 )

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...