在日常 Linux 开发和运维中,find 是一个非常强大的文件搜索工具。除了简单的按文件名查找,它还能按目录、大小、时间、权限,甚至执行批量操作,非常适合多层级目录的管理。本文结合实际案例,带你全面掌握 find 的高级用法。
find [起始路径] [查找条件] [操作]
|
1 2 3 4 5 6 7 8 |
# 查找所有目录 find /path/to/search -type d
# 查找所有普通文件 find /path/to/search -type f
# 查找符号链接 find /path/to/search -type l |
|
1 2 3 4 5 6 7 8 |
# 精确匹配 find . -name "test.txt"
# 忽略大小写 find . -iname "test.txt"
# 通配符匹配 find . -name "*.log" |
|
1 2 3 4 5 6 7 8 |
# 大于 100MB 的文件 find . -type f -size +100M
# 最近 7 天修改过的文件 find . -type f -mtime -7
# 最近 1 小时修改的文件 find . -type f -mmin -60 |
|
1 2 3 4 5 |
# 查找所有 .txt 或 .log 文件 find . \( -name "*.txt" -o -name "*.log" \)
# 查找 .txt 文件且大小 > 1M find . -name "*.txt" -a -size +1M |
逻辑操作符:
|
1 2 3 4 5 6 7 8 |
# 删除找到的临时文件 find . -name "*.tmp" -type f -delete
# 压缩所有 js 文件 find . -name "*.js" -type f -exec gzip {} +
# 使用 + 批量执行,提高效率 find . -name "*.log" -type f -exec gzip {} + |
|
1 2 3 4 5 |
# 空文件 find . -type f -empty
# 空目录 find . -type d -empty |
|
1 2 3 4 5 6 7 8 |
# 权限为 755 的文件 find . -type f -perm 755
# 拥有者为 user 的文件 find . -user user
# 属组为 group 的文件 find . -group group |
|
1 2 3 4 5 |
# 最多查找两级目录 find . -maxdepth 2 -type f
# 从第三级目录开始查找 find . -mindepth 3 -type f |
假设你要查找路径 ./coze-studio/frontend/packages/common 下的文件或目录:
|
1 2 3 4 5 6 7 8 9 10 11 |
# 查找所有文件 find ./coze-studio/frontend/packages/common -type f
# 查找所有目录 find ./coze-studio/frontend/packages/common -type d
# 查找该路径下所有 js 文件 find ./coze-studio/frontend/packages/common -type f -name "*.js"
# 限制查找深度,只查当前目录 find ./coze-studio/frontend/packages/common -maxdepth 1 -type f |
如果你想查找完整路径,例如:
|
1 |
coze-arch/coze-design/icons |
直接用 -name 是找不到的,应该用 -path:
|
1 2 3 4 5 6 7 8 |
# 精确匹配多级路径目录 find / -type d -path "*/coze-arch/coze-design/icons"
# 忽略大小写匹配 find / -type d -ipath "*/coze-arch/coze-design/icons"
# 查找该目录下的 svg 文件 find / -type f -path "*/coze-arch/coze-design/icons/*.svg" |
注意:
|
1 2 3 4 5 6 7 8 |
# 查找大于 100MB 且最近 7 天修改的日志文件并压缩 find /var/log -type f -name "*.log" -size +100M -mtime -7 -exec gzip {} +
# 删除 ./coze-studio/frontend/packages/common 下所有临时文件 find ./coze-studio/frontend/packages/common -type f -name "*.tmp" -delete
# 查找指定多级目录并查看详细信息 find / -type d -path "*/coze-arch/coze-design/icons" -exec ls -lh {} \; |
通过这些组合,可以非常灵活地管理和查找 Linux 系统中的文件和目录,尤其是在多级路径和大型项目中。