如何使 %var% 值多行回声? - 批

How to make a %var% worth multiple lines of echos? - Batch

假设我有一个名为 %Inventory% 的变量

echo %inventory%  

等于

echo %slotOne%  
echo %slotTwo%  
echo %slotThree%  

等等...
有没有办法做到这一点,或者我只需要使用

:Inventory 
cls
echo %slotOne%
echo %slotTwo%
echo %slotThree%
pause<nul
goto ***

您需要制作一个换行符变量,因为批处理没有方便的变量。我从来没有听说过像 Moncraft 建议的那样使用 ALT+10,但这种方法是最接近 "standard" 的方法:

@echo off
setlocal enabledelayedexpansion

set LF=^


:: The above two lines MUST be present or it won't work
set NL=^^^%LF%%LF%^%LF%%LF%

set inventory=%slotOne%%NL%%slotTwo%%NL%%slotThree%

就我个人而言,我建议使用数字代替文字(slot[1]、slot[2]、slot[3] 等),这样您就可以用 for /L循环:

setlocal enabledelayedexpansion
for /L %%A in (1,1,3) do echo !slot[%%A]!

您想要做的是通过 两步过程 显示输出:首先定义一个 "output format"(由您的 "inventory" 变量表示),包括几个数据变量,then 通过单一格式变量的 ECHO 显示所有先前定义的变量的值。这可以通过以下技巧使用 delayed expansion 实现:首先将数据变量存储在用感叹号括起的 "format variable" 中(禁用延迟扩展),然后启用延迟扩展并使用单个 echo %inventory% 扩展以显示所有值:

@echo off
setlocal DisableDelayedExpansion

set LF=^
%empty line 1/2%
%empty line 2/2%

rem Define the "format"
set inventory=!slotOne!!LF!!slotTwo!!LF!!slotThree!

setlocal EnableDelayedExpansion

rem Define a set of values:
set slotOne=Slot one - First set
set slotTwo=Slot two - First set
set slotThree=Slot three - First set

rem Show the first set:
echo First set:
echo %inventory%

rem Define another set of values and show it
set slotOne=Slot one - Second set
set slotTwo=Slot two - Second set
set slotThree=Slot three - Second set
echo/
echo Second set:
echo %inventory%

pause

输出:

First set:
Slot one - First set
Slot two - First set
Slot three - First set

Second set:
Slot one - Second set
Slot two - Second set
Slot three - Second set
Press any key to continue . . .
@ECHO OFF
SETLOCAL
SET "slotone=Sword"
SET "slottwo=Shield"
SET "slotthree=Rock"

SET "inventory=slotone slottwo slotthree"

ECHO Way the first
FOR %%a IN (%inventory%) DO CALL ECHO(%%%%a%%
ECHO ==========================

ECHO Way the second
FOR %%a IN (%inventory%) DO IF DEFINED %%a CALL ECHO(%%%%a%%
ECHO ==========================

ECHO Way the third
FOR %%a IN (%inventory%) DO FOR /f "tokens=1*delims==" %%b IN ('set %%a') DO ECHO(%%c
ECHO ==========================

ECHO Way the fourth
FOR /f "tokens=1*delims==" %%b IN ('set slot') DO ECHO(%%c
ECHO ==========================

SET /a gold=200
SET "header=Your Inventory"
SET "trailer=You have %gold%GP"
ECHO Way the first revisited
FOR %%a IN (header %inventory% trailer) DO CALL ECHO(%%%%a%%
ECHO ==========================
ECHO Way the third revisited
FOR %%a IN (header %inventory% trailer)  DO FOR /f "tokens=1*delims==" %%b IN ('set %%a') DO ECHO(%%c
ECHO ==========================


GOTO :EOF

这是四种不同方式的演示和方法扩展。

前三种方法按照 inventory 中定义的顺序生成列表,而第四种方法依赖于以 slot 开头的变量,并按照分配的变量的字母顺序生成列表(因此 slot01 slot02 等将是首选 - 它更少打字并且本质上可扩展)