首页 > 解决方案 > grep 从两个文件中反向读取匹配模式

问题描述

我有一个文件(请注意,有些行超过 2 列,有些行是 1 个空格分隔的,有些是多个空格分隔的,这个文件很大......)

 file1.txt:
there is a line here that has more than two columns
## this line is a comment
blahblah:     blahblahSierraexample7272
foo: foo@foobar.com
nonsense:                    nonsense59s59S
nonsense:   someRandomColumn
.....

我有另一个文件,它是 file1.txt 的子集,该文件只有两列,列是“1”空格分隔的!

file2.txt
foo: foo@foo.com
nonsense: nonsense59s59S

现在,我想从 file1.txt 中删除 file2.txt 中出现的所有行,如何在 shell 脚本中执行此操作?请注意,第二个文件(file2.txt)只有两列,而 file1.txt 有多个......所以如果需要进行匹配,它应该是:$1(from file2) match $1(from file1)然后$NF(from file2) match $NF(from file1)反转匹配并打印......

PS 已经尝试过grep -vf file2.txt file1.txt了,但是由于 column1 和 $NF 之间的空间没有固定,所以它不起作用...... sed 和 awk 应该可以解决问题,但无法提供代码......

sed -i '/^<firstColumnOfFile2> .* <lastColumnOfFile2>$/d' file1.txt (perhaps in a while loop!)

或类似的东西:grep -vw -f ^[(1stColofFile2)] and also [(lastColOfFile2)]$ file1.txt

标签: bashshellawksedgrep

解决方案


您可以使用sed将行file2.txt转换为与冒号后的一个或多个空格匹配的正则表达式,然后用于grepfile1.txt匹配的行中删除这些行:

$ grep -Evf <(sed 's/^\([^:]*\): /^\1:[[:space:]]+/' file2.txt) file1.txt
there is a line here that has more than two columns
## this line is a comment
blahblah:     blahblahSierraexample7272
foo: foo@foobar.com
nonsense:   someRandomColumn

推荐阅读