Alex k。有一個很好的答案,可能在大多數情況下都很好。 (我upvoted。)
但是,它會破壞包含!
的任何文本。該限制可以通過在循環內開啓和關閉延遲擴展來解決。
該解決方案對於大小合理的文件可能足夠快。但是對於大文件,FOR循環會變得很慢。
我測試了一個包含2817行的190kb文件,並且Alex K.解決方案花了20秒時間進行一次運行。
這是一個完全不同的解決方案,不使用任何循環來處理0中相同的190kb文件。07秒 - 285倍的速度:)
@echo off
setlocal enableDelayedExpansion
set "file=test.txt"
findstr /bv "$ &" "%file%" >"%file%.available"
set "var="
<"%file%.available" set /p "var="
if defined var (
>"%file%.new" (
findstr /b "&" "%file%"
<nul set /p "=&"
type "%file%.available"
)
move /y "%file%.new" "%file%" >nul
)
del "%file%.available"
echo var=!var!
更新:作爲評論的要求,這裏是代碼的大量註釋的版本。
@echo off
setlocal enableDelayedExpansion
:: Define the file to process
set "file=test.txt"
:: Write the unused lines to a temporary "available" file. We don't want any
:: empty lines, so I strip them out here. There are two regex search strings;
:: the first looks for empty lines, the second for lines starting with &.
:: The /v option means only write lines that don't match either search string.
findstr /bv "$ &" "%file%" >"%file%.available"
:: Read the first available line into a variable
set "var="
<"%file%.available" set /p "var="
:: If var defined, then continue, else we are done
if defined var (
REM Redirect output to a "new" file. It is more efficient to redirect
REM the entire block once than it is to redirect each command individulally
>"%file%.new" (
REM Write the already used lines to the "new" file
findstr /b "&" "%file%"
REM Append the & without a new line
<nul set /p "=&"
REM Append the unused lines from the "available" file. The first appended
REM line is marked as used because of the previously written &
type "%file%.available"
)
REM Replace the original file with the "new" content
move /y "%file%.new" "%file%" >nul
)
:: Delete the temp "available" file
del "%file%.available"
:: Display the result
echo var=!var!
我沒有測試過這一點,但我才意識到我可以寫寫入可用線以尋找與比&
以外的字符開頭的行線:
findstr "^[^&]" "%file%" >"%file%.available"
謝謝您!我不明白,但它的作品。謝謝! – idarryl
我真的很抱歉,但是這超出了我的理解水平,我無法理解它將價值(例如蘋果)放在變量中,如果是這樣的話,那麼就是哪一個。如果沒有,我不能確定將腳本放在哪裏。謝謝 – idarryl
在最後一行之後,數值在'!last!'例如'echo value is'!last!'' –