简体   繁体   English

批处理-将命令输出存储到变量(多行)

[英]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%

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. 我知道有一种解决方案,它使用for循环,但不适用于返回多行结果的命令。 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!

But it can be a bit tricky to handle the data later, because of the embedded linefeeds. 但是由于嵌入的换行,以后处理数据可能会有些棘手。
And there is still a limit of 8190 characters per variable. 每个变量仍然有8190个字符的限制。

Often it's easier to use an array. 通常,使用数组更容易。

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]!

looks a bit ugly: 看起来有点难看:

for /f "delims=" %%i in ('dir notexistent.xxx  2^>^&1 1^>nul ') do echo %%i

in-depth-explanation here 这里深入解释

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM