精通 Linux Find 命令选项 | AI生成和翻译

Home 2026.02

find 命令是 Unix/Linux 中用于搜索文件和目录最强大的工具之一。以下是关于其选项和功能的详尽指南。

Basic Syntax

find [path...] [expression]

Starting Points and Paths

你可以指定一个或多个起始目录:

find /home /var /tmp -name "*.log"    # 搜索多个目录
find . -name "file.txt"                # 当前目录
find / -name "config"                  # 整个文件系统

Tests and Filters

基于名称的搜索:

find . -name "*.txt"
find . -iname "README*"
find . -regex ".*\.(jpg|png|gif)"

基于类型的搜索:

find /var -type d -name "log*"
find . -type f -name "*.sh"

基于大小的搜索:

find . -size +100M              # 大于 100MB
find . -size -1k                # 小于 1KB
find /var/log -size +50M -size -100M  # 介于 50-100MB 之间

基于时间的搜索:

find . -mtime -7                # 过去 7 天内修改过
find . -mtime +30               # 超过 30 天前修改过
find . -mmin -60                # 过去 1 小时内修改过
find . -newer reference.txt     # 比 reference.txt 更新

基于权限的搜索:

find . -perm 644                # 精确为 644
find . -perm -644               # 至少为 644
find /bin -perm /u+s,g+s        # 设置了 SUID 或 SGID

基于所有权的搜索:

find /home -user john
find . -nouser                  # 查找孤儿文件

深度控制:

find . -maxdepth 2 -name "*.txt"
find . -mindepth 3 -type f

其他实用测试:

find . -empty -type d           # 空目录
find /usr/bin -executable -type f

Logical Operators

使用逻辑运算符组合测试:

find . -name "*.txt" -o -name "*.md"
find . -type f -not -name "*.log"
find . \\( -name "*.c" -o -name "*.h" \\) -a -mtime -7

Actions

显示操作:

find . -name "*.txt" -print0
find . -printf "%p\t%s bytes\n"

执行操作:

find . -name "*.tmp" -exec rm {} \;
find . -type f -exec chmod 644 {} +
find . -name "*.jpg" -execdir convert {} {}.png \;

删除:

find . -name "*.bak" -delete
find . -type f -empty -delete

其他操作:

find . -name ".git" -prune -o -type f -print

Practical Examples

# 在 home 目录中查找大文件
find ~ -type f -size +500M -exec ls -lh {} \;

# 查找并压缩旧日志文件
find /var/log -name "*.log" -mtime +90 -exec gzip {} \;

# 查找损坏的 symbolic links
find . -type l ! -exec test -e {} \; -print

# 查找今天修改的文件
find . -type f -mtime 0

# 查找全网可写文件(安全检查)
find / -perm -002 -type f 2>/dev/null

# 查找 setuid 文件(安全审计)
find / -perm -4000 -type f 2>/dev/null

# 按扩展名统计文件数量
find . -type f | sed 's/.*\.//' | sort | uniq -c

# 查找重复的文件名
find . -type f -printf "%f\n" | sort | uniq -d

# 清理临时文件
find /tmp -type f -atime +7 -user $(whoami) -delete

Performance Tips

find 命令极其灵活,可以通过管道和命令替换与其他 Unix 工具结合,创建强大的文件管理工作流。


Back Donate