萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

Linux find 指令大全:從檔名搜尋到屬性查詢的完整檔案尋找技巧

Linux 檔案系統龐大複雜,find 是最強大、最靈活的檔案搜尋工具,掌握它等於掌握了 Linux 檔案系統的導航儀。

一、按檔名搜尋

精確檔名

find / -name httpd.conf

從根目錄遞歸搜尋,輸出完整路徑 /etc/httpd/conf/httpd.conf。

忽略權限錯誤輸出

find / -name access_log 2>/dev/null

2>/dev/null 將 stderr(標準錯誤)重導向至空裝置,隱藏「Permission denied」干擾。

縮小搜尋範圍提速

find /etc -name httpd.conf

僅搜尋 /etc 子樹,大幅縮短耗時。

二、按部分檔名/萬用字元搜尋

find /etc -name '*srm*'   # 含 srm 字串
find /etc -name 'srm*'    # 以 srm 開頭
find /etc -name '*.conf'  # 副檔名 .conf

單引號防止 Shell 先展開萬用字元。

三、按檔案屬性搜尋

指令條件
find / -size 1500c大小恰好 1500 bytes(c=bytes,k=KB,M=MB,G=GB)
find / -size +10000000c大於 10MB
find / -size -100k小於 100KB
find / -amin -10最近 10 分鐘被存取
find / -atime -2最近 48 小時被存取
find / -mmin -5最近 5 分鐘被修改
find / -mtime -1最近 24 小時被修改
find / -empty空檔案或空目錄
find / -user fred屬於用戶 fred
find / -group cat屬於群組 cat
find / -nouser無對應用戶(孤兒檔)
find / -nogroup無對應群組
find / -perm 644權限恰好 644
find / -perm -644至少包含 644 權限位
find / -perm /644任一權限位匹配

四、控制選項調整搜尋行為

  • -maxdepth N:限制遞歸深度,find . -maxdepth 2 -name fred 僅搜當前目錄與下一層
  • -mindepth N:最小深度
  • -depth:深度優先(先處理子目錄再處理目錄本身)
  • -follow / -L:追蹤符號連結(預設忽略)
  • -mount / -xdev:不跨越檔案系統邊界
  • -daystart:從今日 00:00 起算時間測試
  • -noleaf:非 Unix 檔案系統(FAT、CD-ROM)優化

五、組合動作:找到後做什麼

find /var/log -name "*.log" -mtime +30 -delete           # 刪除 30 天前舊日誌
find /home -type f -size +100M -exec ls -lh {} \;        # 列出大檔詳細資訊
find /tmp -user www-data -exec chown root:root {} +      # 批次修改擁有者
find / -name "core.*" -exec rm -f {} +                   # 清理 core dump

{} 為佔位符,\; 每個檔案單獨執行,+ 批次傳遞多個檔案(效能更佳)。

六、定位配置檔實戰

不確定 Apache 配置在 /etc/httpd 還是 /etc/apache2?

find /etc -name "httpd.conf" -o -name "apache2.conf"

瞬間定位,無需記憶路徑。

進階替代工具

  • locate/mlocate:資料庫索引,極快但非即時(updatedb 更新)
  • fd:Rust 寫入,預設忽略 .git/.hg、彩色輸出、語法更簡潔
  • ripgrep (rg):內容搜尋王者,亦可 rg --files 列檔案

find 仍是標準、無相依、功能最全的基礎工具,值得深度掌握。

copyright © 萬盛學電腦網 all rights reserved