根据批处理文件中的参数填充文件名

Pad filename based on for parameter in a batch file

我正在使用批处理脚本中的 ImageMagick 为计数器制作图像序列:

for /l %%g in (1,1,20) do imconvert.exe -background none -fill blue -font AVENIRLTSTD-LIGHT -pointsize 72 label:%%g output\%%g.png

这会在输出文件夹中创建名为 1.png2.png3.png 等的文件...

是否可以在上述命令中用零填充 %%g 参数(在 output\%%g.png 部分)?期望的结果是获得名称如 001.png002.png003.png 等的文件...

或者这只能在生成文件后在单独的命令中完成吗?

@echo off
setlocal enableDelayedExpansion
for /l %%g in (1,1,20) do (
    if %%g LSS 100 set name=0%%g
    if %%g LSS 10 set name=00%%g

     imconvert.exe -background none -fill blue -font AVENIRLTSTD-LIGHT -pointsize 72 label:!name! output\!name!.png
)
endlocal

另一种方式:给计数设置一个变量,以足够多的零作为前缀,以保证长度大于或等于你想要的长度。然后使用子字符串操作保留值中的最后 N 个字符(在您的情况下为 3)。

@echo off
setlocal enableDelayedExpansion
for /l %%g in (1,1,20) do (
  set "N=00%%g"
  imconvert.exe -background none -fill blue -font AVENIRLTSTD-LIGHT -pointsize 72 label:!N:~-3! output\!N:~-3!.png
)

就像 npocmaka 一​​样,我也为标签添加了 0 前缀。根据需要进行调整。