Contents

排除具有grep的目录

1. 概述

在 Linux 中,我们经常使用*grep *命令来搜索文件中的文本。grep命令提供了一些使搜索更有效的附加功能。一种这样的功能是在通过目录层次结构重复出现时排除目录。

在本教程中,我们将讨论实现此目的的各种方法。

2. 排除单个目录

让我们创建一组文件和目录以用作示例:

$ mkdir dir1 dir2 dir3 logs nginx-logs
$ echo "This is sample text from dir1/file1.txt file" > dir1/file1.txt
$ echo "This is sample text from dir2/file2.txt file" > dir2/file2.txt
$ echo "This is sample text from dir3/file3.txt file" > dir3/file3.txt
$ echo "This is sample text from logs/service.log file" > logs/service.log
$ echo "This is sample text from nginx-logs/nginx.log file" > nginx-logs/nginx.log

现在让我们看看我们刚刚创建的目录树:

$ tree -h .
.
├── [4.0K]  dir1
│   └── [  45]  file1.txt
├── [4.0K]  dir2
│   └── [  45]  file2.txt
├── [4.0K]  dir3
│   └── [  45]  file3.txt
├── [4.0K]  logs
│   └── [  47]  service.log
└── [4.0K]  nginx-logs
    └── [  51]  nginx.log
5 directories, 5 files

我们可以使用grep命令的*–exclude-dir*选项来排除一个目录:

$ grep -R "sample" --exclude-dir=dir1
logs/service.log:This is sample text from logs/service.log file
dir3/file3.txt:This is sample text from dir3/file3.txt file
dir2/file2.txt:This is sample text from dir2/file2.txt file
nginx-logs/nginx.log:This is sample text from nginx-logs/nginx.log file

在上面的示例中,grep命令在除dir1之外的所有目录中搜索模式。

3. 排除多个目录

我们可以多次使用*–exclude-dir*选项来排除多个目录:

$ grep -R "sample" --exclude-dir=dir1 --exclude-dir=dir2 --exclude-dir=dir3
logs/service.log:This is sample text from logs/service.log file
nginx-logs/nginx.log:This is sample text from nginx-logs/nginx.log file

在上面的示例中,grep命令在除dir 1、dir2dir3之外的所有目录中搜索模式。

有一种替代语法可以实现相同的结果。我们可以花括号中提供目录列表

$ grep -R "sample" --exclude-dir={dir1,dir2,dir3}
logs/service.log:This is sample text from logs/service.log file
nginx-logs/nginx.log:This is sample text from nginx-logs/nginx.log file

请注意,逗号前后不应有任何空格。

4. 使用模式匹配排除目录

如果我们要排除大量目录,有时使用模式匹配会很方便。grep命令支持模式匹配以通过通配符排除目录:

  • ? 表示前一个字符出现零次或一次
  • * 表示前一个字符出现零次或多次
  • \ 用于引用通配符

让我们使用模式dir? 排除dir1dir2dir3 目录:

$ grep -R "sample" --exclude-dir=dir?
logs/service.log:This is sample text from logs/service.log file
nginx-logs/nginx.log:This is sample text from nginx-logs/nginx.log file

让我们使用 logs\* 和 \*logs 模式来排除名称以logs开头或结尾的目录:

$ grep -R "sample" --exclude-dir={logs\*,\*logs}
dir1/file1.txt:This is sample text from dir1/file1.txt file
dir3/file3.txt:This is sample text from dir3/file3.txt file
dir2/file2.txt:This is sample text from dir2/file2.txt file