【问题标题】:Bash script traverse and compare file dates in loopBash 脚本循环遍历和比较文件日期
【发布时间】: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

【问题讨论】:

  • 最终目标到底是什么?你怎么比较? file1which 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


【解决方案1】:

想通了。 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

【讨论】:

  • 很棒 :) 不错的方法 :),只需输入 rm -i $previousEntry 2>/dev/null 以使其更干净
【解决方案2】:

在这里,我只是移动到该目录并删除除最新文件之外的所有文件。

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

【讨论】:

    猜你喜欢
    • 2020-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-23
    • 2013-09-20
    • 2014-11-19
    • 1970-01-01
    相关资源
    最近更新 更多