Contents

使用Grep过滤与指定模式不匹配的行

1. 概述

有时,我们需要过滤与指定模式不匹配的行。在这个快速教程中,我们将快速回顾如何使用grep命令反转多个模式的匹配。grep 命令应该在任何标准 Linux 安装上都可用。

2. 排除作为参数传递的模式

grep命令匹配指定模式之一的输入文本。首先,让我们创建一个文本文件:

$ cat << EOF > /tmp/blogdemo-grep
Time for some thrillin' heroics.
You can't take the sky from me.
May have been the losing side. Still not convinced it was the wrong one.
Every problem is an opportunity in disguise.
EOF

对于我们的实验,我们将过滤不包含单词theevery的行。

2.1. 将模式组合为正则表达式

我们可以形成一个匹配任一单词的正则表达式,并使用-v*标志反转匹配 *:

$ grep -ivw 'the\|every' /tmp/blogdemo-grep
Time for some thrillin' heroics.

*在这里,我们使用带有-w标志的grep将模式视为一个完整的单词。**作为附加说明,-i*标志执行不区分大小写的匹配。

但是,随着模式数量的增加,正则表达式可能会变得冗长且不可读。为了缓解这种情况,我们可以单独指定模式。

2.2. 指定多个模式

-e标志允许我们通过重复使用来指定多个模式。我们可以使用-v标志和-e*标志的重复来排除各种模式:*

$ grep -ivw -e 'the' -e 'every' /tmp/blogdemo-grep
Time for some thrillin' heroics.

我们已经成功过滤了不包含指定模式的行。

3. 排除文件中提到的模式

或者,我们也可以使用-f标志从文件中读取模式,并使用-v*标志反转匹配*。从手册:

-f FILE, --file=FILE
        Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing.

使用文件来保存模式允许我们轻松管理大量模式并重用 shell 历史记录中的命令。让我们创建一个只包含一个模式的文件:

$ echo 'the' > /tmp/blogdemo-grep-patterns
$ grep -wiv -f /tmp/blogdemo-grep-patterns /tmp/blogdemo-grep
Time for some thrillin' heroics.
Every problem is an opportunity in disguise.

让我们在包含我们的模式的文件中添加另一个条目并再次运行grep命令:

$ echo 'every' >> /tmp/blogdemo-grep-patterns
$ grep -wiv -f /tmp/blogdemo-grep-patterns /tmp/blogdemo-grep
Time for some thrillin' heroics.

我们已成功过滤与指定文件中的任何模式不匹配的行。而且,我们可以根据需要继续向我们的模式文件添加更多条目。