find 是 Linux 中最强大、最常用的文件搜索工具,支持复杂条件搜索和批量操作。以下是核心用法整理:
# 精确匹配文件名
find /path -name "filename.txt"
# 通配符搜索(区分大小写)
find . -name "*.log"
# 通配符搜索(不区分大小写)
find /var -iname "*.LOG"# 查找目录
find ~ -type d -name "projects"
# 查找普通文件
find /etc -type f -name "*.conf"
# 查找符号链接
find . -type l
# 查找套接字文件
find /tmp -type s# 在特定路径查找
find /home/user /var/www -name "*.php"
# 排除目录
find . -path "./.git" -prune -o -name "*.js"# 查找大于10MB的文件
find / -size +10M
# 查找小于100KB的文件
find . -size -100k
# 查找大小在1MB到5MB之间的文件
find /var -size +1M -size -5M# 最近7天修改的文件
find /backup -mtime -7
# 7天前修改的文件
find /logs -mtime +7
# 最近24小时访问的文件
find . -atime -1
# 状态变更的文件(权限/所有者)
find /etc -ctime -3# 查找可执行文件
find /usr/bin -perm /u=x
# 查找权限为644的文件
find . -perm 644
# 查找属于用户的文件
find /home -user john
# 查找属于组的文件
find /var/www -group apache# AND 操作(默认)
find . -name "*.tmp" -size +1M
# OR 操作
find / \( -name "*.bak" -o -name "*.tmp" \)
# NOT 操作
find ~ -type f ! -name "*.pdf"# 查找大于1MB的日志文件(排除backup目录)
find / \( -path "/backup" -prune \) -o \
\( -name "*.log" -size +1M \) -print# 打印结果(默认)
find . -name "*.txt"
# 显示详细信息
find /tmp -ls
# 删除文件(谨慎!)
find . -name "*.tmp" -delete# 查找并压缩文件
find /backup -name "*.log" -exec gzip {} \;
# 查找并更改权限
find . -type f -perm 777 -exec chmod 644 {} \;
# 查找并统计行数
find src/ -name "*.py" -exec wc -l {} \;# 一次传递多个文件(更高效)
find ~/photos -name "*.jpg" -exec cp {} /backup/images \+# 交互式确认删除
find . -name "*.old" -ok rm {} \;# 限制搜索深度
find . -maxdepth 2 -name "config.*"
# 设置最小深度
find / -mindepth 3 -name "secret.txt"# 排除特定目录
find / -path "/proc" -prune -o -name "*.conf"
# 排除多个目录
find . \( -path "./.git" -o -path "./node_modules" \) -prune -o -print# 安全处理含空格/特殊字符的文件名
find . -print0 | xargs -0 rm# 删除7天以上的临时文件
find /tmp -type f -mtime +7 -delete# 查找TOP10大文件
find / -type f -size +100M -exec du -h {} + | sort -rh | head -10# 将所有.txt扩展名改为.md
find . -name "*.txt" -exec bash -c 'mv "$0" "${0%.txt}.md"' {} \;# 空文件
find . -type f -empty
# 空目录
find . -type d -empty# 在所有.py文件中搜索"import pandas"
find src/ -name "*.py" -exec grep -l "import pandas" {} \;参数 | 说明 |
|---|---|
-name | 按文件名搜索(区分大小写) |
-iname | 按文件名搜索(不区分大小写) |
-type | 按文件类型(f/d/l/s 等) |
-size | 按文件大小(+10M/-1k) |
-mtime | 按修改时间(天) |
-mmin | 按修改时间(分钟) |
-user | 按文件所有者 |
-perm | 按权限模式 |
-exec | 对匹配文件执行命令 |
-delete | 删除匹配文件 |
-maxdepth | 最大搜索深度 |
-printf | 自定义输出格式 |
提示:使用 -printf 自定义输出:
find . -type f -printf "%p - %s bytes - %TY-%Tm-%Td\n"