find排除文件或目录搜索

前端之家收集整理的这篇文章主要介绍了find排除文件或目录搜索前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

man 信息

man find查看输出的-path选项:

-path pattern
File name matches shell pattern pattern. The Metacharacters do
not treat ‘/’ or ‘.’ specially; so,for example,
find . -path "./sr*sc"
will print an entry for a directory called ‘./src/misc’ (if one
exists). To ignore a whole directory tree,use -prune rather
than checking every file in the tree. For example,to skip the
directory ‘src/emacs’ and all files and directories under it,
and print the names of the other files found,do something like
this:
find . -path ./src/emacs -prune -o -print

Note that the pattern match test applies to the whole file name,
starting from one of the start points named on the command line.
It would only make sense to use an absolute path name here if
the relevant start point is also an absolute path. This means
that this command will never match anything:
find bar -path /foo/bar/myfile -print

The predicate -path is also supported by HP-UX find and will be
in a forthcoming version of the POSIX standard.

从man中得知,可以使用了-path pattern -prune实现,如果想要在排除的结果中继续操作的话可以使用-o 继续处理匹配项。

1、排除某个目录查找:find . -path "pattern" -prune -o -print #在当前目录下查找时pattern要以相对路径开头;如果使用绝对路径查找的话,pattern也要使用绝对路径

2、排除某个文件:find . ! -name filename

3、排除多个目录:find . -path "pattern1" -prune -o -path "pattern2" -prune -o ! -name "." 或

find . -path \( -path pattern1 -o -path pattern2 \) -prune -o -print #使用()

实例

假设kernel_modules目录结构如下:

[root@localhost kernel_modules]# ls -R
.:
hello.c imp1 Makefile proc-module.c


./imp1:
imp1.h imp1_k.c imp1_u imp1_u.c Makefile output

1、列出所有不在imp1目录下的文件

[root@localhost kernel_modules]# find . -path "./imp1" -prune -o ! -name "."

./imp1
./hello.c
./Makefile
./proc-module.c

需要注意的是-path带的参数要为 "./imp1",否则起不到排除imp目录的作用,因为imp1目录下的文件名是./imp1/filename,与imp1 pattern不匹配

2、查找文件名为非*.c的文件

find . ! -name "*.c"

3、排除多个目录

先使用cp imp1 imp2 -r 命令生成imp2目录,然后排除imp1和imp2进行查找

[root@localhost kernel_modules]# find . \( -path "./imp1" -o -path "./imp2" \) -prune -o ! -name "."
./hello.c
./imp1
./imp2
./Makefile

./proc-module.c

使用find . -path "./imp1" -prune -o -path "./imp2" -prune -o ! -name "."效果也一样,有兴趣的话可以自己尝试下

原文链接:https://www.f2er.com/bash/388598.html

猜你在找的Bash相关文章