Linux 下文件搜尋工具豐富,各有適用場景。掌握 which、whereis、find、locate、grep 五大命令,能覆蓋 99% 的查找需求。
| 命令 | 搜尋對象 | 數據源 | 速度 | 典型場景 |
|---|---|---|---|---|
which | 可執行命令路徑 | PATH 環境變量 | 極快 | 確認命令版本、別名 |
whereis | 命令+幫助文檔 | 預建數據庫 | 極快 | 查找二進制、man page、源碼 |
find | 任意文件 | 實時遍歷磁盤 | 較慢 | 複雜條件組合、時間/大小/權限/類型 |
locate | 文件名 | updatedb 數據庫 | 極快 | 模糊名稱快速定位 |
grep | 文件內容 | 實時掃描文件 | 視文件大小 | 日誌分析、代碼搜尋、配置檢查 |
# 1. 按名稱(支持通配符)
find /path -name "*.log"
find /path -iname "readme*" # 忽略大小寫
# 2. 按大小(單位:c=字節 k=KB M=MB G=GB)
find /path -size +100M # 大於 100MB
find /path -size -10k # 小於 10KB
find /path -size 50M # 等於 50MB
# 3. 按所有者/組
find /path -user nginx
find /path -group www-data
# 4. 按時間(天/分鐘)
find /path -mtime -7 # 7天內修改過內容
find /path -atime +30 # 30天前訪問過
find /path -ctime 1 # 1天前狀態改變(權限/屬主等)
find /path -mmin -60 # 60分鐘內修改過
# 5. 按類型
find /path -type f # 普通文件
find /path -type d # 目錄
find /path -type l # 符號鏈接
# 6. 按 inode
find /path -inum 123456
# 7. 多條件組合
find /path -size +10M -a -size -100M -a -name "*.tar.gz"
find /path -user www -o -group www
# 8. 查找後執行動作
find /path -mmin -120 -exec ls -lh {} \;
find /path -name "*.tmp" -delete
find /path -type f -exec chmod 644 {} \;
# 更新數據庫(建議加入 cron 每日執行)
updatedb
# 模糊搜尋
locate nginx.conf
locate -i "*.conf" # 忽略大小寫
locate -c nginx # 僅統計數量
# 基礎用法
grep "error" /var/log/nginx/error.log
grep -r "TODO" /var/www/src/ # 遞歸目錄
grep -n "pattern" file # 顯示行號
grep -i "pattern" file # 忽略大小寫
grep -v "pattern" file # 反向匹配
grep -A5 -B5 "pattern" file # 顯示前後各5行上下文
# 正則表達式
grep -E "^[0-9]{4}-[0-9]{2}" file # 日期開頭
grep -P "\d{3}-\d{3}-\d{4}" file # Perl 正則(電話號碼)
# 找出佔用磁盤最大的 10 個文件
find / -type f -exec du -h {} + 2>/dev/null | sort -hr | head -10
# 找出最近 1 小時被修改的配置文件並備份
find /etc -type f -name "*.conf" -mmin -60 -exec cp -a {} {}.bak \;
# 批量替換文件內容
grep -rl "old_domain.com" /var/www/html | xargs sed -i 's/old_domain.com/new_domain.com/g'