Delete Last line of a text file

October 22, 2009 at 12:45:18
Specs: Windows XP
Hi! I would like to use a batch file to delete the last line of a text file and send the rest of the file to a new text file. I have duplicates rows in my file and need to delete only the last line.

Thank You


See More: Delete Last line of a text file

Report •


#1
October 22, 2009 at 14:00:38
@echo off & setlocal EnableDelayedExpansion > file.new
set /P row=< file.txt
for /F "skip=1 delims=" %%j in (file.txt) do (
  echo.!row!>> file.new
  set row=%%j
)


Report •

#2
October 22, 2009 at 20:25:53
@IVO, the problem with your solution is that blank lines are not preserved.
eg
C:\test>more file
one
two
three

four
five

last

C:\test>test.bat
one
two
three
four
five

@OP, if not a big file, you can use this vbscript

Set objFS=CreateObject("Scripting.FileSystemObject")
strFile = "c:\test\file"
Set objFile = objFS.OpenTextFile(strFile)
arr=Split(objFile.ReadAll,vbCrlf)
For i=LBound(arr) To UBound(arr)-2
	WScript.Echo arr(i)
Next
objFile.Close

GNU win32 packages | Gawk


Report •

#3
October 23, 2009 at 02:43:18
@ghostdog

I am aware of the issue you point out, but I have noticed rarely the posters care of that problem, so I avoid to set up more complex solutions to prevent the loss of blank lines, leaving that code for explicit requests.


Report •

Related Solutions

#4
October 23, 2009 at 07:41:54
it works! thanks

Report •

#5
October 23, 2009 at 08:04:56
Or, if you want an option that is more concise, here's a Perl solution.

This edits the existing file
c:\test>perl -ni.bak -e "print if ! eof" file

This creates a new file
c:\test>perl -ne "print if ! eof" file > newfile


Report •


Ask Question