使用批处理删除文本文件中的最后一行

delete last line in text file using batch

我有文本文件,我只想删除最后一行而不删除空格 我试试这个代码:删除所有空格的最后一行

@Echo Off
SetLocal DisableDelayedExpansion

Set "SrcFile=file.txt"

If Not Exist "%SrcFile%" Exit /B
Copy /Y "%SrcFile%" "%SrcFile%.bak">Nul 2>&1||Exit /B

(   Set "Line="
    For /F "UseBackQ Delims=" %%A In ("%SrcFile%.bak") Do (
        SetLocal EnableDelayedExpansion
        If Defined Line Echo !Line!
        EndLocal
        Set "Line=%%A"))>"%SrcFile%"
EndLocal
Exit /B

我不想再删除最后一行。谢谢

请阅读我在

上的回答

那么批处理文件的代码应该很清楚,它适用于所有 ANSI、OEM 和 UTF-8 编码的文本文件,行号和冒号在每行前面加上 FINDSTR 不超过 8184 个字符。

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "SourceFile=%~1"
if not defined SourceFile set "SourceFile=file.txt"
if not exist "%SourceFile%" echo ERROR: File "%SourceFile%" not found!& exit /B 1

set "Line="
for /F delims^=^ eol^= %%I in ('%SystemRoot%\System32\findstr.exe /N "^" "%SourceFile%" 2^>nul') do (
    setlocal EnableDelayedExpansion
    if defined Line (echo(!Line:*:=!>>"%SourceFile%") else del "%SourceFile%"
    endlocal
    set "Line=%%I"
)
if exist "%SourceFile%" for %%I in ("%SourceFile%") do if %%~zI == 0 del "%SourceFile%"
endlocal

使用第一个参数字符串将其名称传递给批处理文件的源文件或在批处理文件中指定的源文件如果仅包含一行,则将被删除。

如果源文件是空文件,即文件大小为 0 的文件,也会被删除。这是由批处理文件的最后一行完成的。

要了解使用的命令及其工作原理,请打开命令提示符 window,在其中执行以下命令,并仔细阅读为每个命令显示的所有帮助页面。

  • call /? ... 解释 %~1 ... 删除周围 " 的第一个参数。
  • del /?
  • echo /?
  • endlocal /?
  • exit /?
  • findstr /?
  • for /?
  • if /?
  • set /?
  • setlocal /?

另请参阅 single line with multiple commands using Windows batch file 以了解第五行中使用的运算符 & 的说明。