bash grep -v 文件中的多个字符串

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

grep -v multiple strings from file

bashshellksh

提问by Asaf S

I have 2 files:

我有2个文件:

  1. file1
  1. 文件 1

string list:

字符串列表:

ben
john
eric
  1. file2
  1. 文件 2

few rows:

几行:

 ben when to school
 my mother went out
 the dog is big
 john has FB
 eric is nice guy

expoted file :

暴露的文件:

my mother went out
the dog is big

I would like to use grep -vand remove the rows that contains the strings from list.

我想使用grep -v并删除包含列表中字符串的行。

this is the idea but the wrong command :

这是想法,但错误的命令:

grep -v `cat file2` file1 > out

Thanks

谢谢

Asaf

阿萨夫

回答by anubhava

Using a file for patterns:

使用模式文件:

grep -v -f "file2" file1 > out

or else you can do:

否则你可以这样做:

grep -v -e "string1" -e "string2" file1

回答by saeedgnu

If I understand the question correctly, 4 matched lines should be removed one by one, and a single grep can't do it unless you define a REGEXP containing those 4 lines, which is tricky

如果我正确理解了问题,则应将 4 行匹配的行一一删除,除非您定义包含这 4 行的 REGEXP,否则单个 grep 无法执行,这很棘手

But this script should do it

但是这个脚本应该可以做到

cp file2 out
cat file1 | while read STR ; do
    LINE="`grep \"$STR\" file2`"
    sed -i "/^$LINE$/d" out
done

cat out