文件查找 find

find 是最强大的文件搜索工具,可以按名称、类型、大小、时间等多种条件查找文件,还能对找到的文件执行操作。掌握 find 是系统管理的必备技能。

基本语法

find 路径 条件 动作

如果省略路径,默认是当前目录。如果省略动作,默认是打印文件名。

按名称查找

find . -name "*.txt"
find /etc -name "*.conf"
find . -iname "README*"

-name 区分大小写,-iname 不区分大小写。

使用通配符

find . -name "file*"
find . -name "file?.txt"
find . -name "[abc]*"

通配符要用引号包住,防止被 Shell 展开。

按类型查找

-type 指定文件类型:

类型含义
f普通文件
d目录
l符号链接
b块设备
c字符设备
s套接字
p命名管道
find . -type d
find /dev -type b
find . -type f -name "*.sh"

按大小查找

-size 按文件大小查找:

后缀含义
b块(512字节)
c字节
kKB
MMB
GGB
find . -size +100M
find . -size -1k
find . -size 10M

+ 表示大于,- 表示小于,不加表示等于。

按时间查找

按访问时间

-atime 按访问时间查找(天):

find . -atime +7
find . -atime -1

+7 表示7天前,-1 表示1天内。

按修改时间

-mtime 按修改时间查找(天):

find . -mtime -7
find . -mtime +30

按状态改变时间

-ctime 按状态改变时间查找(天):

find . -ctime 0

按分钟

-amin-mmin-cmin 以分钟为单位:

find . -mmin -60
find . -amin +30

按权限查找

-perm 按权限查找:

find . -perm 755
find . -perm -111
find . -perm /222
  • -perm 755:权限正好是 755
  • -perm -111:所有执行位都设置
  • -perm /222:任一写位设置

按用户和组查找

find . -user root
find . -group developers
find . -nouser
find . -nogroup

-nouser-nogroup 查找没有对应所有者或组的文件。

组合条件

与(AND)

默认是 AND 关系:

find . -name "*.txt" -size +1k

或(OR)

-o 表示 OR:

find . -name "*.txt" -o -name "*.md"

非(NOT)

!-not 表示 NOT:

find . ! -name "*.txt"
find . -not -type d

括号分组

find . \( -name "*.txt" -o -name "*.md" \) -size +1k

括号要转义,前后有空格。

对结果执行操作

-exec

-exec 对每个文件执行命令:

find . -name "*.log" -exec rm {} \;
find . -type f -exec chmod 644 {} \;
find . -name "*.txt" -exec grep "error" {} \;

{} 是文件名占位符,\; 是命令结束符。

-exec 的批量模式

-exec ... + 把多个文件传给一个命令:

find . -name "*.txt" -exec grep "pattern" {} +
find . -type f -exec chmod 644 {} +

\; 方式更高效,因为减少了命令调用次数。

-ok

-ok-exec 类似,但会提示确认:

find . -name "*.tmp" -ok rm {} \;

-delete

-delete 删除找到的文件:

find . -name "*.tmp" -delete
find . -type d -empty -delete

-print0 和 xargs

处理文件名包含空格或特殊字符的文件:

find . -name "*.txt" -print0 | xargs -0 grep "pattern"
find . -type f -print0 | xargs -0 chmod 644

-print0 用 null 字符分隔,xargs -0 正确解析。

实用示例

查找大文件

find . -type f -size +100M -exec ls -lh {} \;
find . -type f -size +100M -exec du -h {} \;

查找并删除旧日志

find /var/log -name "*.log" -mtime +30 -delete
find /tmp -type f -mtime +7 -exec rm {} \;

查找空目录

find . -type d -empty
find . -type d -empty -delete

查找最近修改的文件

find . -type f -mtime -1
find . -type f -mmin -60

统计文件数量

find . -type f | wc -l
find . -name "*.txt" | wc -l

查找并打包

find . -name "*.txt" | tar -czf texts.tar.gz -T -

查找并复制

find . -name "*.jpg" -exec cp {} /backup/ \;

小结

  • find 是强大的文件搜索工具
  • -name 按名称,-type 按类型,-size 按大小
  • -mtime 按修改时间,-perm 按权限
  • -exec 对结果执行命令
  • -o 或,! 非,括号分组
  • 配合 xargs 处理特殊文件名