繁体   English   中英

尝试删除子目录中除最近的2个文件以外的所有文件

[英]Trying to delete all but most recent 2 files in sub directories

我正在创建一个cron,它清除除最近两个文件之外的所有指定文件夹的子目录(仅限第一个子目录)但遇到问题。

这些是我的尝试:

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,但数组没有填充所有文件:

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

有人可以帮我解释一下他们是怎么做的吗?

这列出了除最近的两个文件之外的所有文件:

find -type f -printf '%T@ %P\n' | sort -n | cut -d' ' -f2- | head -n -2 

说明:

  • -type f仅列出文件
  • -printf '%C@ %P\\n'
    • %T@ show文件自1970年以来的最后修改时间(以秒为单位)。
    • %P显示文件名
  • | sort -n | sort -n进行数字排序
  • | cut -d' ' -f2- | cut -d' ' -f2-删除秒格式输出,只留下文件名
  • | head -n -2 | head -n -2显示除最后两行之外的所有行

所以要删除所有这些文件,只需通过xargs rmxargs rm -f追加它:

find -type f -printf '%T@ %P\n' | sort -n | cut -d' ' -f2- | head -n -2 | xargs rm

与现有的答案不同,这个NUL分隔了find的输出,因此对于具有绝对任何合法字符的文件名是安全的 - 包含换行符的集合:

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查找)。

我只是遇到了同样的问题,这就是我解决它的方式:

#!/bin/bash

# you need to give full path to directory in which you have subdirectories
dir=`find ~/zzz/ -mindepth 1 -maxdepth 1 -type d`

for x in $dir; do
        cd $x
        ls -t |tail -n +3 | xargs rm --
done

说明:

  • 使用tail -n + number,您可以决定在子目录中保留多少文件

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM