簡體   English   中英

批處理-將命令輸出存儲到變量(多行)

[英]Batch - Store command output to a variable (multiple lines)

我知道這樣做的方法有點像作弊,但是下面的代碼創建了一個臨時文件,然后將其刪除。 我不希望那樣 那么,有沒有合適或更好的方法呢?

command 2>> "temp"
set /p OUTPUT=<"temp"
del "temp"
echo %OUTPUT%

我知道有一種解決方案,它使用for循環,但不適用於返回多行結果的命令。 我想將所有這些存儲到我的變量中。 (我嘗試過此代碼

您可以將其放入包含換行符的單個變量中。

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!

但是由於嵌入的換行,以后處理數據可能會有些棘手。
每個變量仍然有8190個字符的限制。

通常,使用數組更容易。

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

看起來有點難看:

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

這里深入解釋

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM