Skip navigation

JSI Tip 8152. How do I remove the last N lines of a file?


In tip 4574, I scripted Tail.bat to count the number of lines in a file.

Using that technique, I have scripted DelLastLines.bat to remove the last N lines of a file.

The syntax for using DelLastLines.bat is:

DelLastLines FileName \[NumLines\]

Where FileName is the file whose last line(s) you wish to remove, and NumLines is an optional parameter that contains the number of lines to remove. The default is 1.

DelLastLines.bat contains:

@echo off
if \{%1\}

\{\} @echo Syntax: DelLastLines FileName \[NumLines\]&goto :EOF if not exist %1 @echo DelLastLines File %1 not found.&goto :EOF setlocal ENABLEDELAYEDEXPANSION set /a num=1 if not \{%2\}

\{\} set /a num=%2 set wrk="%TEMP%\DelLastLines.tmp" set fle=%1 if exist %wrk% del /q %wrk% for /f %%n in ('find /V /C "" ^>%wrk% ) call :cpy >nul 2>&1 del /q %wrk% endlocal goto :EOF :cpy copy /Y %wrk% %fle%
NOTE: See How can I remove the last N characters of the last line of a file?



Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish