← 中文资源

简体中文版本

find 命令查找与批量处理文件

按名称、大小、修改时间、权限和类型组合筛选文件,并用 -exec、-print0 配合 xargs 批量处理,覆盖常见运维查找场景。

阅读英文原文

功能说明

脚本从 /etc、/var/log、/tmp 和当前目录出发,演示 find 的常见筛选方式:名称通配、大小阈值、修改时间、权限位、空目录以及多条件组合;同时展示 -exec、-printf 和 -print0 | xargs -0 三种后续处理方式,适合日志清理、配置盘点和批量统计。

关键代码

  • find /etc -maxdepth 2 -name "*.conf" -type f 限制搜索深度并按名称与类型过滤,2>/dev/null 屏蔽权限不足的报错。
  • -size +1M 表示大于 1MB,-mtime -1 表示一天内修改,-mtime +30 表示超过 30 天,-perm -o+w 查找其他用户可写的文件。
  • -exec wc -l {} + 把多个文件批量传给命令,比每个文件执行一次更高效。
  • \( -name "*.js" -o -name "*.ts" \) 用括号和 -o 组合条件,括号需转义。
  • -printf "%f\t%k KB\t%TY-%Tm-%Td\n" 自定义输出文件名、占用块数和日期。
  • -print0 与 xargs -0 -P4 以空字符分隔路径,避免文件名中的空格被拆分,并开启 4 路并行。

使用注意

-printf、-perm 等选项在 GNU find 上可用,BSD/macOS 的 find 支持范围不同。搜索系统目录时建议加 -maxdepth 并重定向错误,避免遍历过深。用 -exec 处理用户可控路径时要防止命令注入,优先使用 {} + 传参而非拼接字符串。删除类操作建议先用 -print 确认结果。

验证方式

逐段执行各命令,确认配置文件、超大日志、近期修改文件、空目录和世界可写文件的输出符合预期。可用 find . -name "*.conf" | wc -l 与脚本输出对照,并在含空格的测试文件名下验证 -print0 管道不会拆行。

代码示例

#!/usr/bin/env bash
set -euo pipefail

# Find by name pattern
find /etc -maxdepth 2 -name "*.conf" -type f 2>/dev/null | head -10

# Find by size
echo "=== Large files (>1MB) ==="
find /var/log -type f -size +1M -exec ls -lh {} \; 2>/dev/null | head -5

# Find by modification time
echo "=== Recently modified (last 24h) ==="
find /tmp -type f -mtime -1 2>/dev/null | head -5

echo "=== Old files (>30 days) ==="
find /var/log -type f -mtime +30 -name "*.log" 2>/dev/null | head -5

# Find by permissions
echo "=== World-writable files ==="
find /tmp -type f -perm -o+w 2>/dev/null | head -5

# Find and execute
echo "=== Count lines in config files ==="
find /etc -maxdepth 1 -name "*.conf" -type f -exec wc -l {} + 2>/dev/null | tail -5

# Find with multiple conditions
echo "=== JS or TS files modified recently ==="
find . -type f \( -name "*.js" -o -name "*.ts" \) -mtime -7 2>/dev/null | head -10

# Find empty directories
echo "=== Empty directories ==="
find /tmp -maxdepth 3 -type d -empty 2>/dev/null | head -5

# Find with printf for custom output
echo "=== Formatted output ==="
find /etc -maxdepth 1 -type f -printf "%f\t%k KB\t%TY-%Tm-%Td\n" 2>/dev/null | head -5

# Find newest files
echo "=== 5 newest files ==="
find /var/log -type f -printf "%T@ %p\n" 2>/dev/null | sort -rn | head -5 | cut -d" " -f2-

# Find and process in batches with null delimiter
echo "=== Batch processing ==="
find /etc -name "*.conf" -type f -print0 2>/dev/null |
    xargs -0 -I{} -P4 sh -c "echo Processing: {}; wc -l {}" 2>/dev/null | head -10

# Find with prune to exclude directories
echo "=== Exclude node_modules ==="
find . -type f -name "*.js" -not -path "*/node_modules/*" 2>/dev/null | head -10