萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux 文件搜尋命令大全:which、whereis、find、locate、grep 實戰速查

Linux 下文件搜尋工具豐富,各有適用場景。掌握 which、whereis、find、locate、grep 五大命令,能覆蓋 99% 的查找需求。

命令定位對比

命令搜尋對象數據源速度典型場景
which可執行命令路徑PATH 環境變量極快確認命令版本、別名
whereis命令+幫助文檔預建數據庫極快查找二進制、man page、源碼
find任意文件實時遍歷磁盤較慢複雜條件組合、時間/大小/權限/類型
locate文件名updatedb 數據庫極快模糊名稱快速定位
grep文件內容實時掃描文件視文件大小日誌分析、代碼搜尋、配置檢查

find 進階用法精選

# 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 {} \;

locate 快速定位

# 更新數據庫(建議加入 cron 每日執行)
updatedb

# 模糊搜尋
locate nginx.conf
locate -i "*.conf"  # 忽略大小寫
locate -c nginx     # 僅統計數量

grep 內容搜尋

# 基礎用法
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'
copyright © 萬盛學電腦網 all rights reserved