强大的find命令
2017-05-24 本文已影响39人
寂寞的原子
作为一个命令行重度用户,强大的命令行搜索功能是必不可少的。这里介绍一下系统自带的find
命令,最近结合fzf使用感觉棒棒哒。
find
find的用法如下:
$ find [<options>] <paths> [<expressions>]
<options>
是一些可选的配置,具体参见文档。
<paths>
是搜索的范围,可以有多个目录。
<expressions>
是表达式,可以有多个,下面具体说说这些表达式。
每一个表达式都可以由一些条件和一个操作组成,每个条件都有一个返回值,通过逻辑运算符连接,如果省略逻辑运算符,则相当于AND
运算。
一些常用的条件:
-
-type
:限定搜索对象的类型-
-type f
:普通文件 -
-type d
:目录
-
-
-name
,-iname
:匹配项目名字,-iname
不区分大小写-
-name hello
:完全匹配 -
-name *hello*
:使用通配符
-
-
-path
,-ipath
: 匹配项目绝对路径,-ipath
不区分大小写-
-path /home/gerald/file
:完全匹配 -
-path *hello*
:使用通配符
-
-
-prune
:剪枝
参考 Stack Overflow。
这个操作使find不再搜索匹配到的文件夹的内容,起到剪枝的作用。始终返回true
,因此如果使用OR运算,后续表达式将不再执行,就起到了过滤匹配到的项目的作用。
一些常用的操作:
-
-print
:将结果输出到stdout
,返回true
如果没有指定操作,则默认使用-print
。
一些栗子:
- 列出当前目录下所有文件
$ find . -type f $ find . -type f -print
- 匹配文件名字
$ find . -type f -name foobar $ find . -type f -name foobar -print
- 剪枝
匹配名字是$ find . -name foobar -prune $ find . -name foobar -prune -print
foobar
的项目,如果是文件夹,则不再继续搜索子文件夹。 - 过滤
匹配名字是$ find . -name foobar -prune -o -print
foobar
的项目,由于有OR
操作,匹配结果将被丢弃,不匹配的结果继续执行,因此最终得到的是名字不为foobar
的项目。
在剩下的结果中匹配$ find . -name foobar -prune -o -name foo* -print
foo
开头的项目。如果省略-print
,则相当于最外层应用-print
,如下:
这时名字是$ find . \( -name foobar -prune -o -name foo* \) -print
foobar
的项目也会包括进去,只是剪枝依然有效。