Linux 如何使用 sed\awk 从文件中删除行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13579929/
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-08-06 17:52:55  来源:igfitidea点击:

How to delete lines from file with sed\awk?

linuxbashsedawkfreebsd

提问by evilmind

I have file, with lines, contains ip with netmask a.b.c.d/24 w.x.y.z/32 etc How to delete delete specific row? i'm using

我有带有行的文件,包含带有网络掩码 abcd/24 wxyz/32 等的 ip 如何删除删除特定行?我正在使用

sed -ie "s#a.b.c.d/24##g" %filname%

but after the removal is an empty string in file.

但删除后是文件中的空字符串。

It should run inside a script, with ip as parameter and also work in freebsd under sh.

它应该在脚本中运行,以 ip 作为参数,并且也可以在 sh 下的 freebsd 中运行。

回答by mtk

Sed solution

sed解决方案

 sed -i '/<pattern-to-match-with-proper-escape>/d' data.txt 

-ioption will change the original file.

-i选项将更改原始文件。

Awk solution

awk解决方案

awk '!/<pattern-to-match-with-proper-escape>/' data.txt

回答by Sacx

You should use d (delete) not g. Also do not use s (replacement).

您应该使用 d(删除)而不是 g。也不要使用 s(替换)。

sed -ie '/a.b.c.d\/24/d' %filename%

In a script you should using it in this way

在脚本中,您应该以这种方式使用它

IP=
IPA=${IP////\/}
sed -i /"${IPA}"/d %filename%

And the script parameter should be called in this way:

并且应该以这种方式调用脚本参数:

./script.sh a.b.c.d/24

回答by Guru

Using sed:

使用 sed:

sed -i '\|a.b.c.d/24|d' file

Command line arg:For the input being command line argument, say 1st argument($1):

命令行参数:对于作为命令行参数的输入,请说第一个参数($1):

sed -i "\||d" file

Replace $1 with appropriate argument number as is your case.

根据您的情况,将 $1 替换为适当的参数编号。

回答by Vijay

perl -i -lne 'print unless(/a.b.c.d\/24/)' your_file

or in awk if you donot want to do inplace editing:

或者在 awk 中,如果您不想进行就地编辑:

 awk '##代码##!~/a.b.c.d\/24/' your_file