$ find .../src./src/main.c./tests./tests/bre.tests./Makefile.am$ find srcsrcsrc/main.c$ find src testssrcsrc/main.cteststests/bre.tests在 Linux 下,点号 ‘.’ 对应当前目录,所以 find . 就是查找当前目录下的所有文件,当没有提供目录参数时,默认就是使用 ‘.’ 这个参数 。
find src 命令指定只查找 src 这个目录下的所有文件 。
find src tests 命令指定查找 src、tests 这两个目录下的所有文件,可以同时提供多个目录名来指定查找这些目录 。
find src tests 命令也可以写为 find ./src ./tests 。
如果在 find 命令后面提供文件名,则只在当前目录下查找该文件,不会在子目录下查找:
$ find Makefile.amMakefile.am$ find main.cfind: `main.c': No such file or directory结合上面打印的文件信息,可以看到当前目录下有一个 Makefile.am 文件,find Makefile.am 命令可以找到这个文件,不会报错 。
而 main.c 文件是在 src 子目录下,find main.c 命令执行报错,提示找不到这个文件,它不会进入 src 子目录进行查找 。
注意:前面提到,查找条件要求以 ‘-’、‘(’、或者 ‘!’ 开头,在遇到以这几个字符开头的任意参数之前,前面的参数都会被当作目录参数,指定查找多个目录时,直接在 find 命令后面写上这些目录的路径,用空格隔开即可,不用加上 -o、-path 等选项,加上反而有异常 。
刚接触 find 命令,常见的误区之一就是认为要用 -o 选项来指定查找多个目录 。
例如认为 find src -o tests 是同时查找 src、tests 这两个目录,这是错误的写法,执行会报错:
$ find src -o testsfind: paths must precede expression: tests可以看到,执行报错,提示目录路径参数必须在表达式参数之前提供 。-o 参数以 - 开头,会被认为是表达式参数,它自身、以及在它之后的所有参数都会认为是表达式参数,之后提供的目录名不会被当作要查找的目录 。
某些表达式参数的后面可以提供目录名,但是这些目录名并不是用于指定查找该目录下的文件,而是另有含义 。
另一个误区是,执行 find src -o tests 命令报错后还不知道错在哪里,望文生义,又加上 -path 选项,误写为 find src -o -path tests、或者 find src -path -o tests 。这两个命令都会报错,自行测试即知 。
虽然写为 find src -path tests 不会报错,但是它并不会打印出 src、tests 这两个目录下的文件名 。
后面会具体说明 -path 参数的用法 。
查找时指定忽略一个或多个目录基于上面例子的目录结构,如果想查找当前目录下的文件,且忽略 tests 目录,可以执行下面的命令:
$ find . -path ./tests -prune -o -print../src./src/main.c./Makefile.am可以看到,打印的文件名里面没有 tests 目录名、以及它底下的文件名 。
但是如果把上面 -path 后面的 ./tests 改成 tests,还是会查找 tests 目录下的文件:
$ find . -path tests -prune -o -print../src./src/main.c./tests./tests/bre.tests./Makefile.am这个结果比较奇怪,查找时想要忽略 tests 目录,写为 -path ./tests 可以忽略,写为 -path tests 就不能忽略 。
这是使用 find 命令的 -path 参数时常见的错误,别人的例子可以生效,自己写的时候就不生效 。这需要理解 -path 参数的含义才能正确使用它 。
前面提到,不同的表达式之间要用操作符分隔开,如果没有提供操作符,默认使用 -and 操作符 。
所以 find . -path ./tests -prune -o -print 命令的完整格式其实是 find . -path ./tests -and -prune -o -print 。
下面对这个完整命令格式的各个参数进行详细说明,以便理解它的工作原理,就能知道为什么写为 -path ./tests 可以忽略,写为 -path tests 不能忽略 。
-path pattern这是一个 test 类型表达式,GNU find 在线帮助手册对该表达式的说明如下:
Test: -path pattern即,当 find 命令查找到的文件名完全匹配所给的 pattern 模式时,该表达式返回 true 。
True if the entire file name, starting with the command line argument under which the file was found, matches shell pattern pattern.
To ignore a whole directory tree, use ‘-prune’ rather than checking every file in the tree.
The “entire file name” as used by find starts with the starting-point specified on the command line, and is not converted to an absolute pathname.
这里面最关键的点是,要完全匹配 find 命令查找到的名称,而不是部分匹配,也不是匹配文件的绝对路径名 。
推荐阅读
- ping 域名+端口 Windows和Linux下检测网络是否可用
- 10个实用Linux运维命令
- 在Centos7上安装图形化桌面工具
- 穿衣搭配|化妆师上「高级淡妆」的常用技巧,五星定妆法不怕卡粉、脱妆
- 防晒衣怎么选?教你3个小技巧,买到真正有防晒效果的防晒衣
- 绞股蓝最佳喝的时间,教你九个喝茶的技巧
- 玉兰花茶的泡法,玫瑰花茶泡法技巧
- Linux技巧:awk 命令简单入门介绍
- 如何做网络推广?有哪些渠道和方法?互联网老司机分享推广技巧
- 宫灯长寿花养殖方法及养护技巧
