2014-04-04 100 views
0

我是新的shell腳本。你可以請建議我一些代碼以下要求?保留最近的3個文件夾並刪除其餘的bash腳本?

我有以下格式的文件夾

例如:/home/backup/store_id/datewisefolder/some.zip

,如:/home/backup/44/22032014/some_file.zip

/home/backup/44/23032014/some_file.zip 

    /home/backup/44/24032014/some_file.zip 

    /home/backup/44/25032014/some_file.zip 

還有更多..

我想去每個商店的id文件夾&只保留最近3日期明智的文件夾休息的刪除。這裏44商店id文件夾23032014,24032014,25032014這三個都是最近的一個,所以保持原樣。 22032014年齡較大的刪除一個。

我寫了找出最近三個文件的shell代碼,但我不知道如何使用store_ID文件夾循環刪除休息。

下面的代碼找出最近的文件夾,日期明智

CD /家庭/備份/ 44/ LS -1 | sort -n -k1.8 -k1.4 -k 1 |尾-3

+0

您可以刪除比n更早的文件,比如'find -mtime +3 -delete'刪除超過3天的文件。 –

+0

我不想在時間的基礎上 – Rups

+0

[刪除所有,但最新的X文件在bash中](http://stackoverflow.com/questions/25785/delete-all-but-the-most-recentx -biles-in-bash) – dogbane

回答

0

下面的腳本可以工作。

declare -a axe 
axe=`ls -l /home/backup/* | sort -n -k1.8 -k1.4 -k 1|head -n -3` 

for i in $axe 
do 
    rm -rf $i; 
done 
+0

44 store_id不是常量文件夾它有更多的storeid like 45,46,47,87,98..so在 – Rups

+0

編輯代碼。請檢查。 – vishram0709

0

發現是這類任務的常用工具:

find ./my_dir -mtime +3 -delete 

explaination: 

./my_dir your directory (replace with your own) 
-mtime +3 older than 3 days 
-delete delete it. 

或按腳本代碼

files=(`ls -1 /my_dir | sort -n -k1.8 -k1.4 -k 1 | tail -3`) 

for i in *; do 
keep=0; 
#Check whether this file is in files array: 
for a in ${files[@]}; do 
    if [ $i == $a ]; then 
    keep=1; 
    fi; 
done; 
# If it wasn't, delete it 
if [ $keep == 0 ]; then 
    rm -rf $i; 
fi; 
done 
+0

我沒有常量/ my_dir文件夾。它就像/ home/backup/44,43,56,77,----在那個日期明智的文件夾中,我需要旋轉的文件夾。 – Rups

+0

@ user2481010因此,在'/ home/backup/44,43,56,77'之類的所有目錄中提供路徑,以便使用第一種解決方案。 –

+0

也可以在第二個解決方案命令中使用類似'find/home/backup -type d'的命令來代替'ls'來完成您的工作。 –

0
ls /home/backup | while read store_id 
do 
    count=0 
    ls -t /home/backup/$store_id | while read dir_to_remove 
    do 
    count=$((count + 1)) 
    if [ $count -gt 3 ]; then 
     rm -rf /home/backup/$store_id/$dir_to_remove 
    fi 
    done 
done 
0

光盤放入依次在每個STORE_ID目錄。創建一個具有八位數名稱的目錄列表,按相反順序排列(最近的第一個);最後通過列表的一部分,省略第一個$ retain元素到rm。

basedir=/home/backup 
# How many directories to keep: 
retain=3 

shopt -s nullglob 

# Assuming that anything beginning with a digit is a store_id directory. 
for workdir in "$basedir"/[0-9]*/ ; do 
    (
    cd "$workdir" || exit 1 
    # Create the list. The nullglob option ensures that if there are no 
    # suitable directories, rmlist will be empty. 
    rmlist=(
     $(
      printf '%s\n' [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]/ | 
      sort -nr -k1.5,1.8 -k1.3,1.4 -k1.1,1.2 
     ) 
    ) 
    # If there are fewer than $retain entries in ${rmlist[@]}, rm will be 
    # given no names and so do nothing. 
    rm -rf -- "${rmlist[@]:$retain}" 
) 
done 
相關問題