尝试删除所有,但最近的子目录2档 [英] Trying to delete all but most recent 2 files in sub directories

查看:119
本文介绍了尝试删除所有,但最近的子目录2档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在创建所有的指定文件夹中,清理子目录一个cron(仅适用于第一个孩子),但最近的两个文件,​​但遇到了问题。

I'm creating a cron that cleans subdirectories (first child only) of a specified folder of all but the most recent two files but running into issues.

这是我尝试:

find ./ -type d -exec rm -f $(ls -1t ./ | tail -n +4);
find . -maxdepth 2 -type f -printf '%T@ %p\0' | sort -r -z -n | awk 'BEGIN { RS="\0"; ORS="\0"; FS="" } NR > 5 { sub("^[0-9]*(.[0-9]*)? ", ""); print }' | xargs -0 rm -f

我也尝试创建文件的阵列通过总减2去的打算,但阵列无法与所有文件填充:

I also tried to create an array of files with the intention of going through the total minus 2, but the array was not populating with all files:

while read -rd ''; do      x+=("${REPLY#* }");  done < <(find . -maxdepth 2 -printf '%T@ %p\0' | sort -r -z -n )

可能有人请给我一只手,并解释它们是如何做的?

Could someone please give me a hand and explain how they have done?

推荐答案

与现有的答案,这一个NUL,从划找到输出,因此是安全的文件名以绝对的法律性质 - 一组,其中包括换行符

Unlike the existing answer, this one NUL-delimits the output from find, and is thus safe for filenames with absolutely any legal character -- a set which includes newlines:

delete_all_but_last() {
  local count=$1
  local dir=${2:-.}
  [[ $dir = -* ]] && dir=./$dir
  while IFS='' read -r -d '' entry; do
    if ((--count < 0)); then
      filename=${entry#*$'\t'}
      rm -- "$filename"
    fi
  done < <(find "$dir" \
             -mindepth 1 \
             -maxdepth 1 \
             -type f \
             -printf '%T@\t%P\0' \
           | sort -rnz)
}

# example uses:
delete_all_but_last 5
delete_all_but_last 10 /tmp

请注意,它需要寻找GNU和GNU排序。 (现有的答案还需要GNU FIND)。

Note that it requires GNU find and GNU sort. (The existing answer also requires GNU find).

这篇关于尝试删除所有,但最近的子目录2档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆