Contents

使用FIND命令排除某些路径

1. 概述

作为 Linux 用户,我们经常对文件系统进行各种操作。例如,一种常见的操作是搜索文件。如果系统有大量文件,这个简单的任务会变得很耗时。但是,我们可以通过从搜索路径中排除某些目录来提高效率。

在本教程中,我们将讨论使用*find *命令实现此目的的各种方法。

2. 使用*-prune*选项

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

$ mkdir mp3 jpeg txt
$ touch mp3/1.mp3 mp3/2.mp3 mp3/3.mp3
$ touch jpeg/1.jpeg jpeg/2.jpeg jpeg/3.jpeg
$ touch txt/1.txt txt/2.txt txt/3.txt

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

$ tree 
.
├── jpeg
│   ├── 1.jpeg
│   ├── 2.jpeg
│   └── 3.jpeg
├── mp3
│   ├── 1.mp3
│   ├── 2.mp3
│   └── 3.mp3
└── txt
    ├── 1.txt
    ├── 2.txt
    └── 3.txt

我们可以使用find命令的*-prune*选项来排除某个路径:

$ find . -path ./jpeg -prune  -o -print
.
./txt
./txt/3.txt
./txt/2.txt
./txt/1.txt
./mp3
./mp3/1.mp3
./mp3/2.mp3
./mp3/3.mp3

在上面的示例中,find命令在除jpeg之外的所有目录中执行搜索。

我们还可以使用*-o*运算符排除多个路径

$ find . \( -path ./jpeg -prune -o -path ./mp3 -prune \) -o -print
.
./txt
./txt/3.txt
./txt/2.txt
./txt/1.txt

在上面的示例中,我们使用*-o* 运算符来排除jpegmp3目录。

3. 使用*-not* 运算符

find命令还提供了*-not*运算符。我们可以使用它从搜索路径中排除目录:

$ find . -type f -not -path '*/mp3/*'
./jpeg/3.jpeg
./jpeg/2.jpeg
./jpeg/1.jpeg
./txt/3.txt
./txt/2.txt
./txt/1.txt

在上面的示例中,我们使用*-not运算符从搜索路径中排除mp3*目录。

4. 使用*!*运算符

排除目录的另一种方法是使用*!* 使用find命令的运算符:

$ find . -type f ! -path '*/txt/*'
./jpeg/3.jpeg
./jpeg/2.jpeg
./jpeg/1.jpeg
./mp3/1.mp3
./mp3/2.mp3
./mp3/3.mp3

在上面的例子中,我们使用*!* 运算符排除txt目录。