zsh - 在zsh for循环中,生成以零开头的数字字符串

标签 zsh oh-my-zsh

我有很多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

关于zsh - 在zsh for循环中,生成以零开头的数字字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46985075/

相关文章:

shell - 如何将当前工作目录保存到 Zsh 历史记录?

macos - "Saving wrappers to '/Users/USER/.rvm/bin '........"每次终端打开

zsh - 如何重置 zshrc 文件并将其恢复为默认值?

macos - 每次打开终端时 Zsh 都显示失败

Bash 补全在 ZSH/Oh-My-ZSH 中不起作用,因为 COMP_WORDS 不是数组

shell - ZSH:从使用相同名称的 zsh 函数调用内置函数

bash - 嵌套 if/else 的 zsh 脚本解析器错误

linux - 替换zsh中字符串的一部分

zsh - 是否有可能不使用 zsh 在 tmux 中的 Pane /窗口之间共享历史记录?

regex - grep 替换子字符串时出现意外行为