egrep -v 匹配每行包含一些相同文本的行

egrep -v match lines containing some same text on each line

所以我有两个文件。

文件 1 内容示例。

/n01/mysqldata1/mysql-bin.000001
/n01/mysqldata1/mysql-bin.000002
/n01/mysqldata1/mysql-bin.000003
/n01/mysqldata1/mysql-bin.000004
/n01/mysqldata1/mysql-bin.000005
/n01/mysqldata1/mysql-bin.000006

文件 2 内容示例。

/n01/mysqlarch1/mysql-bin.000004
/n01/mysqlarch1/mysql-bin.000001
/n01/mysqlarch2/mysql-bin.000005

所以我只想根据 mysql-bin.00000X 进行匹配,而不是每个文件中的其余文件路径,因为它们在 file1 和 file2 之间不同。

这是我正在尝试的命令运行

cat file1 | egrep -v file2

我希望这里的输出是...

/n01/mysqldata1/mysql-bin.000002
/n01/mysqldata1/mysql-bin.000003
/n01/mysqldata1/mysql-bin.000006

如有任何帮助,我们将不胜感激。

只需根据 /:

中的所有内容进行比较
$ awk -F/ 'FNR==NR {a[$NF]; next} !($NF in a)' f2 f1
/n01/mysqldata1/mysql-bin.000002
/n01/mysqldata1/mysql-bin.000003
/n01/mysqldata1/mysql-bin.000006

说明

这会读取内存中的文件 2,然后与文件 1 进行比较。

  • -F/ 将字段分隔符设置为 /
  • FNR==NR {a[$NF]; next} 在读取第一个文件 (file2) 时,将每个最后一块存储到数组 a[] 中。由于我们将字段分隔符设置为 /,因此这是 mysql-bin.00000X 部分。
  • !($NF in a) 在读取第二个文件 (file1) 时检查最后一个字段(mysql-bin.00000X 部分)是否在数组 a[] 中。如果没有,打印该行。

I'm having one problem that I've noticed when testing. If file2 is empty nothing is returned at all where as I would expected every line in file1 to be returned. Is this something you could help me with please? – user2841861.

那么问题是读取第二个文件时FNR==NR匹配上了。为了防止这种情况,只需交叉检查 "reading into a[] array" 操作是否在第一个文件上完成:

awk -F/ 'FNR==NR && argv[1]==FILENAME {a[$NF]; next} !($NF in a)' f2 f1
                 ^^^^^^^^^^^^^^^^^^^^

来自 man awk:

ARGV

The command-line arguments available to awk programs are stored in an array called ARGV. ARGC is the number of command-line arguments present. See section Other Command Line Arguments. Unlike most awk arrays, ARGV is indexed from zero to ARGC - 1