bash 删除包含多个字符串之一的行

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

Delete line containing one of multiple strings

bashtextsed

提问by user1899415

I have a text file and I want to remove all lines containing the words: facebook, youtube, google, amazon, dropbox, etc.

我有一个文本文件,我想删除所有包含以下单词的行:facebook, youtube, google, amazon, dropbox, 等。

I know to delete lines containing a string with sed:

我知道用 sed 删除包含字符串的行:

sed '/facebook/d' myfile.txt

I don't want to run this command five different times though for each string, is there a way to combine all the strings into one command?

我不想为每个字符串运行这个命令五次,有没有办法将所有字符串组合成一个命令?

回答by gpojd

Try this:

尝试这个:

sed '/facebook\|youtube\|google\|amazon\|dropbox/d' myfile.txt

From GNU's sed manual:

来自GNU 的 sed 手册

regexp1\|regexp2

Matches either regexp1or regexp2. Use parentheses to use complex alternative regular expressions. The matching process tries each alternative in turn, from left to right, and the first one that succeeds is used. It is a GNU extension.

regexp1\|regexp2

匹配regexp1regexp2。使用括号来使用复杂的替代正则表达式。匹配过程从左到右依次尝试每个选项,并使用第一个成功的选项。它是一个 GNU 扩展。

回答by glenn Hymanman

grep -vf wordsToExcludeFile myfile.txt

"wordsToExcludeFile" should contain the words you don't want, one per line.

“wordsToExcludeFile”应包含您不想要的单词,每行一个。

If you need to save the result back to the same file, then add this to the command:

如果您需要将结果保存回同一个文件,请将其添加到命令中:

 > myfile.new && mv myfile.new myfile.txt

回答by jaypal singh

With awk

awk

awk '!/facebook|youtube|google|amazon|dropbox/' myfile.txt > filtered.txt