bash SED/tr 等。:如何注释掉文件中包含“字符串”的行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24883826/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 10:55:38  来源:igfitidea点击:

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

regexbashsedtr

提问by Jotne

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 ?

我怎样才能通过 SED 或通过命令行的其他方法来做到这一点?

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 )

最实用的方法是什么?( 最快的 )

回答by Avinash Raj

Through sed,

通过sed,

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

Add inline edit -ioption to save the changes made.

添加内联编辑-i选项以保存所做的更改。

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

回答by Jotne

This awkwould do too.

awk也行。

awk '/2001/ {##代码##="#"##代码##}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