Alex K.提供的答案在大多数情况下可能都很好。(我赞同。)
然而,它会破坏任何包含!
的文本。可以通过在循环内切换延迟扩展来解决这个限制。
对于大多数大小合理的文件,该解决方案可能足够快。但是,对于大型文件,FOR循环可能变得非常缓慢。
我测试了一个包含2817行的190kb文件,Alex K.的解决方案需要20秒才能运行一次。
以下是一种完全不使用任何循环的完全不同的解决方案,可以在0.07秒内处理相同的190kb文件-速度快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"
!last!
。例如:echo value is '!last!'
。 - Alex K.