【发布时间】:2013-05-06 04:36:13
【问题描述】:
所以我想比较文件夹中文件的修改日期。我知道您可以将其与 -nt 或 -ot 进行比较,但我不知道如何遍历文件并进行比较。我知道您必须将文件分配为前一个文件,但我不知道该文件的代码。
例如,我有一个文件夹,其中包含 3 个文件 a、b 和 c。在 for 循环中,我想将 a(上一个条目)与 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
【问题讨论】:
-
最终目标到底是什么?你怎么比较?
file1与which file? -
上一个条目是什么??如果你最终告诉我们你想做什么,可能还有其他方法。如果你想在某个给定日期之前删除文件
older,递归地,它可以在一行中完成。 (older是个难词~~) -
你提到的,是这样的吗?
for i in *; do if [ -n $j ]; then if [ $i -nt $j ]; then echo "$j newer than $i"; fi; fi; j=$i; done?假设您按上述顺序创建了 3 个文件 a、b、c,因此您将得到a newer than b; b newer than c;作为输出。 -
是的,这就是我想要的。
-
那么最终你会得到最新创建的文件,所以为什么不使用
ls -t|head -1
标签: bash file date loops compare