[英]Recursively delete all files except a certain number in each directory
我在目錄中包含大量文件進行測試。 我需要為應用程序保留目錄結構,但想對文件進行精簡以進行更快的測試。 我想將目錄的文件數限制為3。如何在Linux中做到這一點?
為了闡明我要完成的工作,請使用Python解決方案:
import sys, os
for root, dirs, files in os.walk(sys.argv[1]):
for index, file in enumerate(files):
if index > int(sys.argv[2]) - 1: os.remove(os.path.join(root, file))
用法:
python thinout.py /path/to/thin\ out/ <maximum_number_of_files_per_directory>
例:
python thinout.py testing\ data 3
我會在bash中執行以下操作:
for dir in `find . -type d`; pushd $dir; rm `ls | awk 'NR>3'`; popd; done;
或者此版本可能更好:
for dir in `find . -type d`; pushd $dir; rm `find . -maxdepth 1 -type f | tail -n +3`; popd; done;
當然-僅隨機刪除目錄中除前3個文件之外的所有文件總是有些冒險。 買家當心...
順便說一句,我自己沒有對此進行測試。 只需輸入想到的內容即可。 您可能需要對其進行一些微調才能使其正常工作。 再次,買家要當心。
這個相當冗長的序列將處理包含空格等的文件,並將前三個按字母順序排序的文件保留在每個子目錄中。
編輯:應用mklement的改進來處理需要轉義的目錄。
find /var/testfiles/ -type d -print0 | while IFS= read -r -d '' subdir; \
do cd "$subdir"; find . -mindepth 1 -maxdepth 1 -type f -print0 | \
sort --zero-terminated | tr '\0' '\n' | tail -n+4 | tr '\n' '\0' | \
xargs --null --no-run-if-empty rm ; cd "$OLDPWD" ; done
由於我的tail版本不支持行終止符使用--zero
或--null
標志,因此我必須使用tr
解決該問題。 歡迎提出改進建議。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.