批处理 - 将命令输出存储到变量(多行) [英] Batch - Store command output to a variable (multiple lines)
问题描述
我知道一种有点像作弊的方法,但下面的代码会创建一个临时文件,然后将其删除.我不希望这种情况发生.那么有没有合适的或更好的方法呢?
I know a way of doing this which is a bit like cheating but the code below creates a temporary file and then deletes it. I don't want that happen. So is there a proper or better way of doing it?
command 2>> "temp"
set /p OUTPUT=<"temp"
del "temp"
echo %OUTPUT%
我知道有一个使用 for 循环的解决方案,但它不适用于返回多行结果的命令.我想将它们全部存储到我的变量中.(我试过这个代码顺便说一句)
I know there is a solution which uses for loop but that doesn't work for commands which return more than one line of result. I want to store all of them into my variable. (I tried this code btw)
推荐答案
您可以将其放入包含换行符的单个变量中.
You can put it into a single variable with including linefeeds.
setlocal EnableDelayedExpansion
set LF=^
REM The two empty lines are required here
set "output="
for /F "delims=" %%f in ('dir /b') do (
if defined output set "output=!output!!LF!"
set "output=!output!%%f"
)
echo !output!
但是由于嵌入了换行符,以后处理数据可能会有点棘手.
每个变量仍然有 8191 个字符的限制.
But it can be a bit tricky to handle the data later, because of the embedded linefeeds.
And there is still a limit of 8191 characters per variable.
通常使用数组更容易.
setlocal EnableDelayedExpansion
set "output_cnt=0"
for /F "delims=" %%f in ('dir /b') do (
set /a output_cnt+=1
set "output[!output_cnt!]=%%f"
)
for /L %%n in (1 1 !output_cnt!) DO echo !output[%%n]!
这篇关于批处理 - 将命令输出存储到变量(多行)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!