语法格式
find [路径] [选项] [操作]
选项
- -name:根据文件名查找
- -perm:根据文件权限查找
- -prune:排除某些查找目录
- -user:根据文件属主查找
- -group:根据文件属组查找
- -mtime -n | +n:根据文件更改时间查找
- -nogroup:查找无有效属组的文件
- -nouser:查找无有效属主的文件
- -newer file1 ! file2:查找更改时间比 file1 新但比 file2 旧的文件
- -type:按文件类型查找
- -size -n +n:按文件大小查找
- -mindepth n:从 n 级子目录开始搜索
- -maxdepth n:最多搜索到 n 级子目录
- -a:与
- -o:或
- -not | !:非
操作
- -print 打印输出
- -exec 对搜索到的文件执行特定的操作,格式为 -exec ‘command’ {} \;
例子1:搜索 /etc 下的文件(非目录),文件名以 conf 结尾,且大于 10k,然后将其删除
find ./etc/ -type f -name ‘*.conf’ -size +10k -exec rm -f {} \;
例子2: 将 /var/log/ 目录下以 log 结尾的文件,且更改时间在 7 天以上的删除
find /var/log/ -name ‘*.log’ -mtime +7 -exec rm -rf {} \;
例子3: 搜索条件和例子1 一样,只是不删除,而是将其复制到 /root/conf 目录下
find ./etc/ -size +10k -type f -name ‘*.conf’ -exec cp {} /root/conf/ \;
- -ok 和 exec 功能一样,只是每次操作都会给用户提示
命令总结
常用选项
- –name 查找 /etc 目录下以 conf 结尾的文件 find /etc -name ‘*conf’
- –iname 查找当前目录下文件名为 aa 的文件,不区分大小写 find . -iname aa
- -user . 查找文件属主为 hdfs 的所有文件 find . user hdfs
- -group . 查找文件属组为 yarn 的所有文件 find . -group yarn
- -type
- f 文件 find . -type f
- d 目录 find . -type d
- c 字符设备文件 find . -type c
- b 块设备文件 find . -type b
- l 链接文件 find . -type l
- p 管道文件 find . -type p
- –size
- -n 大小大于 n 的文件
- +n 大小小于 n 的文件
- n 大小等于 n 的文件
例子1: 查找 /etc 目录下小于 10000 字节的文件
find /etc -size -10000c
例子2: 查找 /etc 目录下大于 1M 的文件
find /etc -size +1M
- –mtime
- -n n 天以内修改的文件
- +n n 天之外修改的文件
- n 正好 n 天修改的文件
例子1: 查找 /etc 目录下 5 天之内修改且以 conf 结尾的文件
find /etc -mtime -5 -name ‘*.conf’
例子2: 查找 /etc 目录下 10 天之前修改且属主为 root 的文件
find /etc -mtime +10 -user root
- -mmin
- -n n 分钟以内修改的文件
- +n n 分钟以外修改的文件
例子1: 查找 /etc 目录下 30 分钟之前修改的文件
find /etc -mmin +30
例子2: 查找 /etc 目录下 30 分钟之内修改的目录
find /etc -mmin -30 -type d
- -mindepth n 表示从 n 级子目录开始搜索
例子:在 /etc 下的 3 级子目录开始搜索
find /etc -mindepth 3
- -maxdepth n 表示最多搜索到 n-1 级子目录
- 一级子目录就是当前路径
例子1:在 /etc 下搜索符合条件的文件,但最多搜索到 2 级子目录
find /etc -maxdepth 2 -name ‘*.conf’
例子2: 在 /etc 下搜索后缀以 .conf 结尾的文件且文件大小为 10k 以上,且最多搜索到 2 级子目录
find /etc/ -type f -name ‘*.conf’ -size +10k -maxdepth 2
了解选项
- -nouser 查找没有属主的用户
例子:find . -type f -nouser
- -nogroup
例子:find . -type f -nogroup
- -perm
例子:find . -perm 664
- -prune
通常和 -path 一起使用,用于将特定目录排除在搜索条件之外
例子1: 查找当前目录下所有普通文件,但排除 test 目录
find . -path ./etc -prune -o -type f
例子2: 查找当前目录下所有普通文件,但排除 etc 和 opt 目录
find . -path ./etc -prune -o -path ./opt -prune -o -type f
例子3: 查找当前目录下所有普通文件,但排除 etc 和 opt 目录,但属主为 hdfs
find . -path ./etc -prune -o -path ./opt -prune -o -type f -a -user hdfs
例子4: 查找当前目录下所有普通文件,但排除 etc 和 opt 目录,但属主为 hdfs,且文件大小必须大于 500 字节
find . -path ./etc -prune -o -path ./opt -prune -o -type f -a -user hdfs -a -size +500c-newer file1