understanding find (by hanlray(at)gmail.com)
一个典型的查找请求描述如下:
查找foo目录树下名字为bar的文件,不查找mount上的子目录,然后把查找到的文件名打印出来
- 查找的目录树,这里是foo
- 匹配条件,这里是名字为bar的文件
- 查找选项,这里是不查找mount上的子目录
- 对匹配的文件执行的动作,这里是把它们的文件名打印出来
find是如何表达由这几个要素构成的查找请求呢?
find [-H][-L][-P][path...][expression]
expression由谓词表达式options、tests和actions组成,它们之间由operator连接,可以表达复杂的查找逻辑:
- options指定查找选项,针对整个查找操作,永远返回true
- tests指定匹配条件,测试文件是否满足匹配条件
- actions指定对匹配文件执行的动作
- operator包括否、与、或等,根据其优先级对expression进行求值,在求值的过程中完成查找。
options、tests和actions的写法,除了极个别的几个,用的都是Linux/Unix command中通用的short option的形式:短横杠后跟option name,如果有参数的话隔一个空格跟在后面。
常用tests:
-
-name <pattern>
- 基于文件名的匹配 -iname <pattern>
- 和-name一样,忽略大小写 -type <c>
- 测试文件类型,<c>的值为:
- d directory
- f regular file
常用actions:
-
-print
- 打印匹配的文件名,如果没有指定action则是缺省action -delete
- 删除文件,如果删除成功则返回true -exec command;
- 执行某个命令,如果返回状态为0则返回true,可以在命令中用'{}'代表当前文件
常用options:
-
-mount
- 不查找mount的目录
常用operators:
-
expr1 expr2
- 表示与,如果expr1为false则不对expr2求值
examples
-
find .
- 这里没有写expression,-print为缺省action,因此将打印当前目录下(包括当前目录)的所有文件,包括子目录及子目录下的文件。 find . -type f
- 查找当前目录树下所有的普通文件并打印出来