有這個任務幾種解決方案。
第一個在交換奇數行和偶數行的批處理文件的所有行執行時使用延遲擴展。這意味着它不適用於行中帶有感嘆號的行,因爲!
已從行中刪除。
@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "SourceFile=%USERPROFILE%\Desktop\TestFile.txt"
if not exist "%SourceFile%" goto EndBatch
set "TargetFile=%USERPROFILE%\Desktop\TestFile2.txt"
del "%TargetFile%" 2>nul
set "LineOdd="
for /F "usebackq delims=" %%I in ("%SourceFile%") do (
if not defined LineOdd (
set "LineOdd=%%I"
) else (
echo %%I>>"%TargetFile%"
echo !LineOdd!>>"%TargetFile%"
set "LineOdd="
)
)
if defined LineOdd echo !LineOdd!>>"%TargetFile%"
move /Y "%TargetFile%" "%SourceFile%"
:EndBatch
endlocal
空白和空行被FOR跳過,因此在目標文件丟失。並且以分號;
開頭的行在讀取每行時被忽略FOR並且因此在輸出文件中也缺少該行。根據輸入的例子,這些限制在這裏不重要。
第一溶液的侷限性可以用本批處理代碼這是當然慢得多來避免:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "SourceFile=%USERPROFILE%\Desktop\TestFile.txt"
if not exist "%SourceFile%" goto EndBatch
set "TargetFile=%USERPROFILE%\Desktop\TestFile2.txt"
del "%TargetFile%" 2>nul
set "LineOdd="
for /F "tokens=1* delims=:" %%H in ('%SystemRoot%\System32\findstr.exe /N /R "^" "%SourceFile%"') do (
if not defined LineOdd (
set "LineOdd=_%%I"
) else (
if "%%I" == "" (
echo/>>"%TargetFile%"
) else (
echo %%I>>"%TargetFile%"
)
setlocal EnableDelayedExpansion
if "!LineOdd!" == "_" (
echo/>>"%TargetFile%"
) else (
echo !LineOdd:~1!>>"%TargetFile%"
)
endlocal
set "LineOdd="
)
)
if defined LineOdd (
setlocal EnableDelayedExpansion
if "!LineOdd!" == "_" (
echo/>>"%TargetFile%"
) else (
echo !LineOdd:~1!>>"%TargetFile%"
)
endlocal
)
move /Y "%TargetFile%" "%SourceFile%"
:EndBatch
endlocal
這將是還可以使用由Dave貝納姆書面混合批處理文件JREPL.BAT:
call jrepl.bat "^(.*)\r\n(.*)\r\n" "$2\r\n$1\r\n" /M /X /F "%USERPROFILE%\Desktop\TestFile.txt" /O "%USERPROFILE%\Desktop\TestFile2.txt"
move /Y "%USERPROFILE%\Desktop\TestFile2.txt" "%USERPROFILE%\Desktop\TestFile.txt"
如果在使用此解決方案時是偶數行,則該文件的最後一行必須具有DOS/Windows行終止符(回車符\ r和換行符\ n)。
要了解使用的命令/可執行文件/批處理文件及其工作方式,請打開命令提示符窗口,在其中執行以下命令行,並仔細閱讀爲每個命令/可執行文件/批處理文件顯示的所有幫助頁面。
del /?
echo /?
endlocal /?
findstr.exe /?
for /?
goto /?
if /?
jrepl.bat /?
move /?
set /?
setlocal /?
閱讀也是微軟的文章關於Using Command Redirection Operators爲2>nul
和>>
的解釋。
爲什麼每個文件路徑都有雙反斜槓?我曾經使用的每臺PC上的每個文件路徑都有一個反斜槓。 – Compo
這是我的習慣,它的工作原理 – andybelous2
[錯誤](https://msdn.microsoft.com/en-gb/library/windows/desktop/aa365247(v = vs.85).aspx#paths),更改你的壞習慣! – Compo