2017-07-19 116 views
0

我想寫一個腳本來刪除最小的文件,如果文件夾內有多個小於10MB的文件,但我沒有成功。shell腳本以條件刪除小於xMB的文件

在我嘗試

find . -type f -size -10M -exec rm {} +

移除所有小於10 MB,我需要的,如果該文件夾內有超過10MB遞歸較小的2個文件,只除去最小。

任何可以幫助我嗎?

回答

0

一個選項是遍歷的find的輸出,然後繼續接着大量的文件的跟蹤和追蹤最小的文件,所以在最後,你可以將其刪除:

#!/bin/bash 

path=/path/to/dir # replace here with your path 

while read -d '' -r dir;do 

    files_count=0 
    unset min 
    unset smallest_file 

    while read -d '' -r file;do 

      let files_count++ 
      min_size="$(du -b "${file}"|cut -f1)" 
      min=${min:-"$min_size"} 
      smallest_file=${smallest_file:-"$file"} 

      if ((min_size < min));then 
        min=$min_size 
        smallest_file=$file 
      fi 

    done < <(find "${dir}" -type f -size -10M -maxdepth 1 -print0) 

    if ((files_count >= 2));then 

      echo "$smallest_file" 
      #rm -v "$smallest_file" 

    fi 

done < <(find "${path}" -type d -print0) 
+0

所以,不要」 t在這裏工作: 'find:'smallest':沒有這樣的文件或目錄' 從我的理解中,它將刪除其中最小的一個。但是,如果在該文件夾中有大於10MB的文件> = 2個文件,我只需要刪除最小的文件夾。 –

+0

@YagoLima對不起,這是我的測試目錄,替換爲你的目錄路徑,我編輯了代碼。 – archemiro

+0

我的不好,已經改變了。但是,正如我所說,它只顯示了其中最小的一個。如果在該文件夾中有小於10MB的文件> = 2,則需要該文件夾中的最小文件。 –