我创build了一个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
我也尝试创build一个文件的数组,目的是通过总减2,但数组并没有填充所有文件:
while read -rd ''; do x+=("${REPLY#* }"); done < <(find . -maxdepth 2 -printf '%T@ %p\0' | sort -r -z -n )
有人能请我帮忙解释他们是如何做的?
与现有的答案不同的是,这个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查找)。
这列出了除最近两个文件外的所有文件:
find -type f -printf '%T@ %P\n' | sort -n | cut -d' ' -f2- | head -n -2
说明:
-type f
列出唯一的文件 -printf '%C@ %P\n'
%T@
显示文件自1970年以来的最后修改时间(秒)。 %P
显示文件名称 | sort -n
| sort -n
做一个数字排序 | cut -d' ' -f2-
| cut -d' ' -f2-
删除秒表格输出,只留下文件名 | head -n -2
| head -n -2
显示除最后两行外的所有内容 所以要删除所有这些文件,只需通过xargs rm
或xargs rm -f
添加管道即可:
find -type f -printf '%T@ %P\n' | sort -n | cut -d' ' -f2- | head -n -2 | xargs rm
我只是遇到了同样的问题,我就是这样解决的:
#!/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
说明: