Bash脚本:删除最旧的目录

6

我想查找最老的目录(在一个目录中),并将其删除。我正在使用以下命令:

rm -R $(ls -1t | tail -1)

ls -1t | tail -1确实会给出最旧的目录,但问题在于它不会删除该目录,并且还会列出文件。

请问我该如何修复这个问题?

4个回答

8
rm -R "$(find . -maxdepth 1 -type d -printf '%T@\t%p\n' | sort -r | tail -n 1 | sed 's/[0-9]*\.[0-9]*\t//')"

这也适用于目录名包含空格、制表符或以"-"开头的情况。

3
这不是很优美,但它可以工作:
rm -R $(ls -lt | grep '^d' | tail -1  | tr " " "\n" | tail -1)

小心:如果目录名包含空格,它将无法正常工作。 - Giuseppe Cardone

0
rm -R $(ls -tl | grep '^d' | tail -1 | cut -d' ' -f8)

0


find directory_name -type d -printf "%TY%Tm%Td%TH%TM%TS %p\n" | sort -nr | tail -1 | cut -d" " -f2 | xargs -n1 echo rm -Rf
You should remove the echo before the rm if it produces the right results


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接