“for file in”以数字而不是字母顺序?

Phi*_*ide 5 shell bash wildcards

我有一个脚本根据文件夹中的每个文件生成索引。所有文件名都是带扩展名的数字。

如何修改我的循环以按数字顺序处理它们?

for file in xml/*.xml; do
  ...
done
Run Code Online (Sandbox Code Playgroud)

Ini*_*ian 8

如果您可以GNU sort选择在\0分隔符上取消限制,您可以这样做。这样,while循环将开始按排序顺序获取文件供您处理。printf用您自己的自定义逻辑替换该选项。

shopt -s nullglob

printf '%s\0' xml/*.xml | sort -zV | while read -rd '' file; do
    printf "%s\n" "$file"
done

shopt -u nullglob
Run Code Online (Sandbox Code Playgroud)

nullglob如果xml在当前文件夹中没有找到文件,该选项是为了防止 shell 扩展空的 glob 。-u处理完成后,该选项会取消设置。


正如Tony Speight正确指出的那样,如果您不想弄乱 shell 选项(例如它可能因其他原因被启用),您可以在子 shell 中进行设置并让 glob 扩展发生

( shopt -s nullglob; printf '%s\0' xml/*.xml ) | sort -zV |  while read -rd '' file; do
    printf "%s\n" "$file"
done
Run Code Online (Sandbox Code Playgroud)


Gil*_*il' 5

如果可以使用zsh(对于脚本来说,就是方便开发和方便部署的权衡):

for file in xml/*.xml(n); do
  ...
done
Run Code Online (Sandbox Code Playgroud)

的水珠限定符 n指定对订购匹配的glob模式时,数字序列必须根据该整数的数值顺序它们代表,而不是在字典顺序排列,即,foo10bar后来foo9bar。

您还可以setopt numeric_glob_sort使用此设置使所有 glob 模式使用此设置。