Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove the last line from the text file (including empty lines) using batch

Tags:

batch-file

My text file

Header
A,B,C,D,E
F,G,H,I,J
K,L,M,N,O
Footer

I want remove the Footer and also empty lines below Footer (Empty lines are not static) And my expected output

Header
A,B,C,D,E
F,G,H,I,J
K,L,M,N,O

I tried the below code, But it removing the last empty line alone.

set row=
for /F "delims=" %%j in (file.txt) do (
  if  defined row echo.!row!>> newfile.txt
  set row=%%j
)
like image 949
Arun Nadaraj Avatar asked Oct 19 '25 13:10

Arun Nadaraj


1 Answers

This would be a generic way to perform the task; If you want something different consider providing more specific information and example file(s):

@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

You should change your filename on line 4 to match your actual source file's name. If you are happy with the result you can optionally delete the .bak file, (which is a backup of the original file, saved for safety).

Note: The resultant file will end with the normal CRLF, (i.e there will be a blank line at the bottom).

like image 163
Compo Avatar answered Oct 22 '25 06:10

Compo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!