在 zsh for 循环中,零前导数字字符串生成

In zsh for loop, zero-leading number string generation

我有很多 part-00001、part-00002... 文件。

我想这样使用:

for ((i=0;i<1000;i++)); do <some command> <formatted string with i>; done.

如何在 zsh 中用数字 i 格式化类似于 "part-000xx" 的字符串?

可以通过以下方式完成:

  • typeset -Z 5 i(使用内置 typeset -Z [N]
  • printf "part-%05d" $i(使用内置 printf "%05d" $i
  • ${(l:5::0:)i}(使用参数扩展标志l:expr::string1:string2:

如下所示:

    typeset -Z 5 j
    for ((i=0;i<1000;i++)); do
      # <some command> <formatted string with i>
      j=$i; echo "part-$j" # use $j here for sure the effects of below 2 lines
      echo "$(printf "part-%05d" $i)"
      echo "part-${(l:5::0:)j}"
    done
    # This outputs below:
    # >> part-00000
    # >> part-00000
    # >> part-00000
    # >> part-00001
    # >> part-00001
    # >> part-00001
    # >> ...
    # >> part-00999

这是每个项目的描述。


typeset
-Z [N]
Specially handled if set along with the -L flag. Otherwise, similar to -R, except that leading zeros are used for padding instead of blanks if the first non-blank character is a digit. Numeric parameters are specially handled: they are always eligible for padding with zeroes, and the zeroes are inserted at an appropriate place in the output.
-- zshbuiltins(1), typeset, Shell Builtin Commands


printf
Print the arguments according to the format specification. Formatting rules are the same as used in C.
-- zshubuiltins(1), printf, Shell Builtin Commands


l:expr::string1::string2:
Pad the resulting words on the left. Each word will be truncated if required and placed in a field expr characters wide.
The arguments :string1: and :string2: are optional; neither, the first, or both may be given. Note that the same pairs of delimiters must be used for each of the three arguments. The space to the left will be filled with string1 (concatenated as often as needed) or spaces if string1 is not given. If both string1 and string2 are given, string2 is inserted once directly to the left of each word, truncated if necessary, before string1 is used to produce any remaining padding.
-- zshexpn(1), Parameter Expansion Flags