Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Linux 刪除指定檔案外所有檔案的 5 種實用方法

編輯:關於 Linux

在 Linux 目錄中「保留特定檔案,刪除其餘所有檔案」是常見的清理需求。本文提供 5 種不同複雜度與適用場景的方法,從簡單的 Shell 擴展到強大的 find 組合,總有一款適合你的場景。

基礎刪除指令回顧

  • 刪除檔案:rm filename
  • 刪除目錄 (含內容):rm -rf dirname
  • 僅刪除空目錄:rmdir dirname

方法一:移動保留檔案 → 清空目錄 → 移回 (最直觀,適合新手)

mkdir -p /tmp/backup
mv keep_file /tmp/backup/      # 移動需保留的檔案/目錄到暫存區
rm -rf *                       # 刪除當前目錄所有內容
mv /tmp/backup/keep_file ./    # 移回原位
rmdir /tmp/backup

優點:邏輯清晰,不需記憶特殊語法。
缺點:需額外磁碟空間與移動時間;大量檔案時較慢。

方法二:Shell 擴展模式 !(pattern) (最快捷,需啟用 extglob)

shopt -s extglob          # 啟用擴展模式 (bash 預設通常已開啟)
rm -rf !(keep_file)       # 刪除除 keep_file 外的所有檔案
rm -rf !(keep1|keep2)     # 保留多個檔案/目錄

注意:! 為模式否定,| 為或條件。此法僅適用於當前目錄,不遞迴子目錄。

方法三:ls + grep -v + xargs (經典管道組合)

ls | grep -v '^keep_file$' | xargs rm -rf

解析:
ls 列出檔名 → grep -v 排除完全匹配 keep_file 的行 → xargs rm -rf 批次刪除。
優點:支援正則表達式,可精準匹配複雜檔名模式。
缺點:檔名含空白、換行等特殊字元時 xargs 可能出錯 (建議改用 xargs -d '\n' 或 find -print0 | xargs -0)。

方法四:find + grep -v + xargs (可指定目標目錄)

find ./test_dir -maxdepth 1 -type f | grep -v 'keep_file' | xargs rm -f

改進點:find 可指定任意目錄 (./test_dir),-maxdepth 1 僅處理第一層,-type f 僅匹配檔案 (不含目錄)。更精確可控。

方法五:純 find 配合 -name 模式否定 (最高效,單一進程)

# 刪除不以 keep 開頭的檔案
find . -maxdepth 1 -type f ! -name 'keep*' -delete

# 或使用 regex (更靈活)
find . -maxdepth 1 -type f ! -regex './keep.*' -delete

優點:
1. find 內建 -delete 動作,單一進程完成遍歷與刪除,效能最佳。
2. 支援 -maxdepth、-type、-name、-regex 等豐富條件組合。
3. 正確處理特殊字元檔名,無需擔心 xargs 分隔符問題。
推薦:生產環境大量檔案清理首選。

進階場景:保留特定副檔名、保留最近 N 天檔案

# 保留所有 .log 檔案,刪除其他
find . -maxdepth 1 -type f ! -name '*.log' -delete

# 保留 7 天內修改過的檔案,刪除更舊的
find . -maxdepth 1 -type f -mtime +7 -delete

# 組合:刪除 30 天前且非 .bak 的檔案
find . -maxdepth 1 -type f -mtime +30 ! -name '*.bak' -delete

安全提醒

  1. 先預覽:將 -delete 或 rm 替換為 ls 或 echo 確認匹配列表無誤後再執行刪除。
  2. 備份重要資料:操作前確認已有備份或快照。
  3. 小心 .* 隱藏檔:上述指令預設不匹配隱藏檔 (以 . 開頭),若需包含隱藏檔請調整模式或加上 -name '.*' 條件。

根據檔案量、檔名複雜度、是否需要遞迴子目錄、腳本自動化需求,選擇最適合的方法。日常互動操作推薦 方法二;腳本自動化與大量檔案清理首選 方法五。

Copyright © Windows教程網 All Rights Reserved