bash 如何从一组文件中删除与模式匹配的所有行?

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

How do I remove all lines matching a pattern from a set of files?

bashsedgreppattern-matching

提问by John Lawrence Aspden

I've got an irritating closed-source tool which writes specific information into its configuration file. If you then try to use the configuration on a different file, then it loads the old file. Grrr...

我有一个令人讨厌的闭源工具,它可以将特定信息写入其配置文件。如果您随后尝试在不同的文件上使用配置,则会加载旧文件。咕噜噜...

Luckily, the configuration files are text, so I can version control them, and it turns out that if one just removes the offending line from the file, no harm is done.

幸运的是,配置文件是文本文件,所以我可以对它们进行版本控制,结果证明,如果只是从文件中删除有问题的行,也不会造成任何伤害。

But the tool keeps putting the lines back in. So every time I want to check in new versions of the config files, I have to remove all lines containing the symbol openDirFile.

但是该工具不断地将行放回原处。所以每次我想签入新版本的配置文件时,我都必须删除所有包含符号的行openDirFile

I'm about to construct some sort of bash command to run grep -v on each file, store the result in a temporary file, and then delete the original and rename the temporary, but I wondered if anyone knew of a nice clean solution, or had already concocted and debugged a similar invocation.

我即将构建某种 bash 命令来对每个文件运行 grep -v,将结果存储在一个临时文件中,然后删除原始文件并重命名临时文件,但我想知道是否有人知道一个不错的干净解决方案,或者已经编造和调试过类似的调用。

For extra credit, how can this be done without destroying a symbolic link in the same directory (favourite.rc->signals.rc)?

额外的功劳,如何在不破坏同一目录(favourite.rc->signals.rc)中的符号链接的情况下做到这一点?

回答by Kent

sed -i '/openDirFile/d' *.conf

this do the removing on all conf files

这会删除所有 conf 文件

you can also combine the line with "find" command if your conf files are located in different paths.

如果您的 conf 文件位于不同的路径中,您还可以将该行与“find”命令结合使用。

Note that -i will do the removing "in place".

请注意, -i 将“就地”进行删除。

回答by John Lawrence Aspden

This was the bash-spell that I came up with:

这是我想出的 bash-spell:

for i in *.rc ; do TMP=$(mktemp) ; grep -v openDirFile ${i} >${TMP} ; mv ${TMP} ${i} ; done

Kent's answer is clearly superior.

肯特的回答显然更胜一筹。