
將輸出重定向到帶有>
.例如:
for /l %%n in (1,1,10000) do (echo %%n>>output.txt)
或者:
for /l %%n in (1,1,10000) do (call:sub %%n)
exit
:sub
(echo %1)>>output.txt
exit /b
其中任何一個都會建立一個列出數字 1 到 10,000 的文字檔案。
但是,這些範例會將每一行輸出單獨寫入磁碟,而且我不喜歡每次執行這些批次檔時對我的 SSD 進行 10,000 次單獨寫入的想法。
那麼,無論如何,我是否可以在操作進行時將其生成的輸出排隊到內存中,然後在最後一次寫入中將整個輸出寫入磁碟?一些進階的重定向技巧?或者也許有某種方法可以將正在進行的輸出儲存在變數中,以便稍後使用 echo 重定向%output%>>output.txt
?
筆記:以上只是範例,無需建議建立編號清單的替代方法!我的查詢是一般性的,涉及將輸出重定向到文字文件,同時避免逐行磁碟寫入。
答案1
那麼,無論如何,我是否可以在操作進行時將其生成的輸出排隊到內存中,然後在最後一次寫入中將整個輸出寫入磁碟?一些進階的重定向技巧?或者也許有某種方法可以將正在進行的輸出儲存在變數中,稍後使用 echo %output%>>output.txt 進行重定向?
當然是。使用 powershell。
powershell 的美妙之處在於,您可以將所有內容轉儲到變數、陣列或字典中,然後最後在一次寫入中將其完全寫入磁碟。
這是一個例子:
myscript.ps1:
# create the output variable that we'll write to disk later.
$output = @()
1..10000|foreach-object {
#get the number: (this line is optional, but just to make it easier to understand)
$number = $_
#add the number to the output
$output += $number
}
#print the output to the screen:
$output
#write the output to a file:
$output|out-file -FilePath "output.txt"
您當然可以替換整個數字。您需要知道的是:
# create the variable:
$output = @()
# Add to it
$output += "something"
# Write it to disk:
$output|out-file -FilePath "output.txt"
答案2
你試試看:
@echo off & cd /d "%~dp0"
>.\log.txt =;(
for /l %%L in (1,1,10000)do echo/%%~L
);=
筆記:以上只是範例,無需建議建立編號清單的替代方法!我的查詢是一般性的,涉及將輸出重定向到文字文件,同時避免逐行磁碟寫入。
>redirect_file (
use command blocks
)
要完全從bat的執行中重定向結果,您還可以執行它並將此執行重定向到最終文件,其中第一個調用檢查文件是否已通過,如果沒有,bat會對自身運行進行第二次調用並這次將其結果重定向到一個文件,如下所示:
@echo off && setlocal enableextensions
rem :: checks if the variable has received value ::
if /i "!_log!/" == "/" (
echo/Batch call started: !date! - / - !time!
rem :: If it has not received any value, it will assign and call the bat itself
set "_log="%temp%\log_bat.log"" && echo/>!_log! & "%~0" >>!_log! & exit /b
rem :: As soon as it has received some value, the bat will continue executing, already saving in: !_log!
) else endlocal
:: your current code in bat starts at that point saving the outputs in "%temp%\log_bat.log” ::
...