Zsh:删除除字典顺序最高的文件以外的所有文件

Zsh: Delete all files except the one in highest lexicographic sorting order

我有一组文件匹配特定的 glob 模式(比如:*.txt)。我想删除所有这些,除了字典顺序最高的那个。

我试图找到各种解决方案,但即使是我提出的最好的解决方案也很丑陋:

set -A files *(N)
set -A to_remove ${(O)files}
shift to_remove
foreach f in $to_remove
do
  echo rm $f
done

(我没有写rm $to_remove,因为如果to_remove为空会报错)

如果您知道更简单的方法,请提供一些建议。

您不需要先创建数组;您可以指定一个范围来过滤文件名扩展返回的文件。

$ touch a b c
$ print -l *(N)
a
b
c
$ print -l *(N[1,-2])
b
c

因此,您可以使用 rm *(N[1,-2]) 删除第一个匹配文件以外的所有文件。

你可以用数组做同样的事情:

$ foo=(a b c)
$ print -l $foo[2,-1]
b
c

如果文件名在排序数组中,请使用 subscript range;负数从末尾算起。

if ((#files > 1)); then rm -- ${files[1,-2]}; fi

如果数组未排序,sort it first

if ((#files > 1)); then rm -- ${${(o)files}[1,-2]}; fi

如果您只是为此生成文件,则可以从 glob qualifier.

中进行选择
files=(*.txt(N[1,-2]))
if ((#files)); then rm -- $files; fi