[英]Trying to delete all but most recent 2 files in sub directories
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. 我正在创建一个cron,它清除除最近两个文件之外的所有指定文件夹的子目录(仅限第一个子目录)但遇到问题。
These are my attempts: 这些是我的尝试:
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
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: 我还试图创建一个文件数组,目的是通过总减2,但数组没有填充所有文件:
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? 有人可以帮我解释一下他们是怎么做的吗?
This lists all but the most recent two files: 这列出了除最近的两个文件之外的所有文件:
find -type f -printf '%T@ %P\n' | sort -n | cut -d' ' -f2- | head -n -2
Explanation: 说明:
-type f
list only files -type f
仅列出文件 -printf '%C@ %P\\n'
%T@
show file's last modification time in seconds since 1970. %T@
show文件自1970年以来的最后修改时间(以秒为单位)。 %P
show the file name %P
显示文件名 | sort -n
| sort -n
do a numeric sort | sort -n
进行数字排序 | cut -d' ' -f2-
| cut -d' ' -f2-
drop the seconds form output, leave only the filename | cut -d' ' -f2-
删除秒格式输出,只留下文件名 | head -n -2
| head -n -2
show all but the last two lines | head -n -2
显示除最后两行之外的所有行 So to remove all these files just append pipe it through xargs rm
or xargs rm -f
: 所以要删除所有这些文件,只需通过xargs rm
或xargs rm -f
追加它:
find -type f -printf '%T@ %P\n' | sort -n | cut -d' ' -f2- | head -n -2 | xargs rm
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: 与现有的答案不同,这个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
Note that it requires GNU find and GNU sort. 请注意,它需要GNU查找和GNU排序。 (The existing answer also requires GNU find). (现有的答案也需要GNU查找)。
I just hit the same problem and that's how I solved it: 我只是遇到了同样的问题,这就是我解决它的方式:
#!/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
Explanation: 说明:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.