2013-05-06 69 views
0

所以我想比較文件夾中文件的修改日期。我知道你可以將其與-nt或-ot進行比較,但我不知道如何遍歷文件並進行比較。我知道你必須指定一個文件作爲前一個文件,但我不知道這個代碼。Bash腳本遍歷和比較循環中的文件日期

例如,我有一個文件夾與說3文件,a,b和c。在for循環中,我想比較(先前的條目)和b(條目)。如果a比b新,則刪除b。等等。

我想弄清楚如何分配「以前的條目」。

謝謝親切!

echo "Which directory would you like to clean?" 
read directory 
echo "Are you sure you want to delete old back ups? Y for yes" 
read decision 
if [ $decision = "y" ] 
then 
for entry in "$directory"/* 

do 
#need to somehow assign the previous entry and current entry to a variable 
if [ $entry -nt $previousEntry ] 
rm -i $previousEntry 
echo "Deleted $previousEntry" 
fi 
done 
echo "Deleted all old files" 

else 
echo "Exiting" 
exit 1 
fi 
+0

到底什麼是最終目標?你怎麼比較? 'file1'與'哪個文件'? – Bill 2013-05-06 04:38:08

+0

什麼是以前的入口?如果你最終告訴我們你想要做什麼,可能還有其他方法。如果你想刪除比某個給定日期更舊的文件,遞歸地,它可以在一行中完成。 (「老」是一個難詞~~) – abasu 2013-05-06 04:44:32

+0

你提到的是這樣的事情嗎? '因爲我在*;如果[-n $ j];那麼如果[$ i -nt $ j];然後回顯「$ j比$ i更新」;網絡連接;網絡連接; J = $ I; done'?假設你有3個文件,a,b,c按照上述順序創建,所以你會得到一個比b更新的文件; b比c更新;'作爲輸出。 – abasu 2013-05-06 05:08:44

回答

0

想通了。 2嵌套for循環。謝謝我。

echo "Which directory would you like to clean?" 
read directory 
echo "Are you sure you want to delete old back ups? Y for yes" 
read decision 
if [ $decision = "y" ] 
then 

# Beginning of outer loop. 
for entry in "$directory"/* 
do 
    # Beginning of inner loop. 
    for previousEntry in "$directory"/* 

    do 
if [[ $entry -nt $previousEntry ]] #nt = newer than 
then 
echo "$entry is newer than $previousEntry" 
echo "Deleting $previousEntry" 
rm -i $previousEntry 
fi 
    done 
    # End of inner loop. 

done 

fi #end first if 
+0

偉大的:)很好的方法:),只是把'rm -i $ previousEntry 2>/dev/null'使它更清潔 – abasu 2013-05-06 10:40:38

0

在這裏,我只是移動到該目錄,並刪除除最新的文件之外的所有文件。

echo "Which directory would you like to clean?" 
read directory 
echo "Are you sure you want to delete old back ups? Y for yes" 
read decision 
if [ $decision = "y" ] 
then 
cd $directory 
ls -tr | head --lines=-1|xargs rm -f ; 
echo "Deleted all old files" 

else 
echo "Exiting" 
exit 1 
fi