亚历克斯·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"