Windows 循环和续行的批处理文件

Windows Batch File for loop and line continuation

我需要一个脚本来填充 3 x 3 网格中 5 个块的所有可能组合。所以我想我可以使用 ImageMagick 进行着色并使用 txt 文件进行输入。文本文件由每行一个数字组成,数字显示哪个块应该被着色。 5 个数字构成一种可能的组合。

我使用 for 循环逐行读取我的 txt 文件。变量(称为 a)递增,当它达到 5 时重置为 0,另一个变量(称为 n)递增,这会更改输出文件的名称。由于每次开始新组合时我都需要重新加载原始图像,因此我使用另一个变量(名称)在每个组合的原始图像和图片之间切换。

这是我第一次写批处理文件。所以我可能还没有完全理解行延续和变量的工作原理,因为我的脚本没有产生任何输出。

setlocal ENABLEDELAYEDEXPANSION
set a=0
set n=0
for /F %%G in (test.txt) do ^
set /A a=a+1 & ^
if !a!==5 set a=0  & set /A n=n+1 & ^
if !a!==0 set name=original.png else set name=output_!n!.png ^
if %%G == 1 magick convert -fill blue -draw "color 50, 50 floodfill" %name% output_!n!.png ^
if %%G == 2 magick convert -fill blue -draw "color 150, 50 floodfill" %name% output_!n!.png ^
if %%G == 3 magick convert -fill blue -draw "color 250, 50 floodfill" %name% output_!n!.png ^
if %%G == 4 magick convert -fill blue -draw "color 50, 150 floodfill" %name% output_!n!.png ^
if %%G == 5 magick convert -fill blue -draw "color 150, 150 floodfill" %name% output_!n!.png ^
if %%G == 6 magick convert -fill blue -draw "color 250, 150 floodfill" %name% output_!n!.png ^
if %%G == 7 magick convert -fill blue -draw "color 50, 250 floodfill" %name% output_!n!.png ^
if %%G == 8 magick convert -fill blue -draw "color 150, 250 floodfill" %name% output_!n!.png ^
if %%G == 9 magick convert -fill blue -draw "color 250, 250 floodfill" %name% output_!n!.png
Pause

您的代码仅经过重新格式化,(除了新的第一行):

@echo off
setlocal ENABLEDELAYEDEXPANSION
set a=0
set n=0
for /F %%G in (test.txt) do (
    set /A a=a+1
    if !a!==5 (set a=0)
    set /A n=n+1
    if !a!==0 (set name=original.png) else (set name=output_!n!.png)
    if %%G==1 (magick convert -fill blue -draw "color 50, 50 floodfill" !name! output_!n!.png)
    if %%G==2 (magick convert -fill blue -draw "color 150, 50 floodfill" !name! output_!n!.png)
    if %%G==3 (magick convert -fill blue -draw "color 250, 50 floodfill" !name! output_!n!.png)
    if %%G==4 (magick convert -fill blue -draw "color 50, 150 floodfill" !name! output_!n!.png)
    if %%G==5 (magick convert -fill blue -draw "color 150, 150 floodfill" !name! output_!n!.png)
    if %%G==6 (magick convert -fill blue -draw "color 250, 150 floodfill" !name! output_!n!.png)
    if %%G==7 (magick convert -fill blue -draw "color 50, 250 floodfill" !name! output_!n!.png)
    if %%G==8 (magick convert -fill blue -draw "color 150, 250 floodfill" !name! output_!n!.png)
    if %%G==9 (magick convert -fill blue -draw "color 250, 250 floodfill" !name! output_!n!.png)
)
Pause

我更新了代码以修复您的名称变量的一个主要问题。