通过 Bash 删除 FreeBSD 上除 X 个最旧目录外的所有目录(无 -printf,带空格,无 zsh)
removing all but X oldest directories on FreeBSD via Bash (no -printf, with spaces, no zsh)
关于目录中 find/removing 最旧 directory/files 的 Whosebug 上有几个不同的主题。我已经阅读了很多,看到了无数不同的方法,这些方法显然适用于其他系统上的某些人,但在我的特定情况下不适用于我。
约束是:
- 我在 FreeBSD (Freenas 9.3)
- 目录中有空格
- 不要使用 ls (http://mywiki.wooledge.org/ParsingLs)
- 无法使用 find 的 -printf(对我来说不存在)
我得到的最接近的是这样的(不完整):
find . -maxdepth 1 -d -name "Backup Set*" -print0 | xargs -0 stat -f "%m %N" | sort -r| awk 'NR>5'
这给了我要删除的目录,但是它们现在有时间戳,我不确定如果我剥离并通过管道传输到 rm,我会回到无法删除带空格的目录的情况在他们里面。
输出:
1450241540 ./Backup Set1
1450241538 ./Backup Set0
在此感谢您的帮助。
我看过的相关帖子:
https://superuser.com/questions/552600/how-can-i-find-the-oldest-file-in-a-directory-tree
Bash scripting: Deleting the oldest directory
Delete all but the most recent X files in bash
... | awk 'NR>5' | while read -r timestamp filename; do rm -rf "${filename}"; done
当字段多于 read
中指定的变量时,其余部分简单地集中在最后指定的变量中。在我们的例子中,我们提取时间戳并按原样使用其他所有内容作为文件名。我们迭代输出和 运行 每个条目的 rm
。
我建议使用 echo
而不是 rm
进行测试 运行,这样您可以先验证结果。
或者,如果您更喜欢 xargs -0
版本:
... | awk 'NR>5' | while read -r timestamp filename; do printf "%s[=11=]" "${filename}"; done | xargs -0 rm -rf
这也使用了 while read
,但打印每个文件名时都带有空字节定界符,可以被 xargs -0
摄取。
管道这个剪切命令cut -d ' ' -f 2-
将取出时间戳
简单的例子
echo '1450241538 ./Backup Set0'|cut -d ' ' -f 2-
将去掉时间戳
结果会是
./Backup Set0
关于目录中 find/removing 最旧 directory/files 的 Whosebug 上有几个不同的主题。我已经阅读了很多,看到了无数不同的方法,这些方法显然适用于其他系统上的某些人,但在我的特定情况下不适用于我。
约束是:
- 我在 FreeBSD (Freenas 9.3)
- 目录中有空格
- 不要使用 ls (http://mywiki.wooledge.org/ParsingLs)
- 无法使用 find 的 -printf(对我来说不存在)
我得到的最接近的是这样的(不完整):
find . -maxdepth 1 -d -name "Backup Set*" -print0 | xargs -0 stat -f "%m %N" | sort -r| awk 'NR>5'
这给了我要删除的目录,但是它们现在有时间戳,我不确定如果我剥离并通过管道传输到 rm,我会回到无法删除带空格的目录的情况在他们里面。
输出:
1450241540 ./Backup Set1
1450241538 ./Backup Set0
在此感谢您的帮助。
我看过的相关帖子:
https://superuser.com/questions/552600/how-can-i-find-the-oldest-file-in-a-directory-tree
Bash scripting: Deleting the oldest directory
Delete all but the most recent X files in bash
... | awk 'NR>5' | while read -r timestamp filename; do rm -rf "${filename}"; done
当字段多于 read
中指定的变量时,其余部分简单地集中在最后指定的变量中。在我们的例子中,我们提取时间戳并按原样使用其他所有内容作为文件名。我们迭代输出和 运行 每个条目的 rm
。
我建议使用 echo
而不是 rm
进行测试 运行,这样您可以先验证结果。
或者,如果您更喜欢 xargs -0
版本:
... | awk 'NR>5' | while read -r timestamp filename; do printf "%s[=11=]" "${filename}"; done | xargs -0 rm -rf
这也使用了 while read
,但打印每个文件名时都带有空字节定界符,可以被 xargs -0
摄取。
管道这个剪切命令cut -d ' ' -f 2-
将取出时间戳
简单的例子
echo '1450241538 ./Backup Set0'|cut -d ' ' -f 2-
将去掉时间戳
结果会是
./Backup Set0