如何让%var%值得多行回声? - 批量

时间:2015-02-22 06:26:51

标签: batch-file

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

echo %inventory%  

等于

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

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

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

3 个答案:

答案 0 :(得分:2)

您要做的是通过两步程序显示输出:首先定义一个由多个数据变量组成的“输出格式”(由“库存”变量表示),以及然后通过单一格式变量的ECHO显示所有先前定义的变量的值。通过此技巧可以使用延迟扩展:首先将数据变量存储在感叹号中的“格式变量”中(禁用延迟扩展),然后启用延迟扩展并使用单个{{1扩展以显示所有值:

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

答案 1 :(得分:1)

您需要制作换行变量,因为批次没有一个方便。我从来没有听说像Moncraft所说的那样使用ALT + 10,但这种方式与#34;标准最接近&#34;这样做的方式:

@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%

就个人而言,我建议使用插槽的数字而不是单词(插槽[1],插槽[2],插槽[3]等),以便您可以使用for /L循环调用所有内容:

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

答案 2 :(得分:1)

@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等会更受欢迎 - 它的输入次数更少,内在可扩展性更高)