Bash Shell脚本FOR遍历早于特定日期的文件

时间:2020-10-07 08:47:27

标签: bash shell

我正在尝试识别和删除Shell脚本中早于某个固定日期的文件。下面是一个仅对其进行计数的脚本。我不能使用find或其他任何会建立参数的东西,因为此目录中有150万个文件,我得到了

-bash: /usr/bin/find: Argument list too long

错误。所以我当前的缩写脚本是:

y=0;
cond=$(date -d 2020-10-15 +%s)
for FILE in *tele*
do
  if [ $FILE -ot $cond ]
  then
    y=$((y+1))
  fi
done
echo $y

它应该计算所有文件(计算日期是将来的日期),但会重新调整为0。我认为我没有使用正确的日期类型进行比较。

1 个答案:

答案 0 :(得分:2)

这是计数文件的简单技巧:

find … -printf x | wc -c

基本上,对于每个文件,打印字节“ x”,然后计算字节数。


关于脚本失败的原因,-ot的摘要为[ PATH1 -ot PATH2 ],您可以像这样(未经测试)轻松模拟它:

reference="$(mktemp)"
touch "--date=@${cond}" "$reference"
…
if [[ "$path" -ot "$reference" ]]
then
    …

运行时比较:

$ cd "$(mktemp --directory)"
$ touch {1..100000}
$ time find . -mindepth 1 -printf x | wc -c
100000

real    0m0.072s
user    0m0.036s
sys     0m0.040s
$ time for FILE in *
do
   if [ $FILE -ot 0 ]
   then
       y=$((y+1))
   fi
done

real    0m0.438s
user    0m0.334s
sys     0m0.105s

对于100000个文件,find解决方案的速度提高了约6倍。

相关问题