アレックス K. ほとんどの状況でおそらく問題ない良い答えがあります。(私は賛成票を投じました。)
ただし、 を含むテキストは破損します!
。この制限は、ループ内で遅延展開のオンとオフを切り替えることで修正できます。
このソリューションは、ほとんどの合理的なサイズのファイルに対して十分に高速である可能性があります。ただし、大きなファイルの場合、FOR ループは非常に遅くなる可能性があります。
2817 行を含む 190kb のファイルをテストしたところ、Alex K. のソリューションは 1 回の実行に 20 秒かかりました。
これは、同じ 190kb ファイルを 0.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"