0

所以我想比较文件夹中文件的修改日期。我知道您可以将其与 -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
4

2 回答 2

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
于 2013-05-06T08:12:58.860 回答
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
于 2013-05-06T10:28:53.800 回答