Computing.Net > Forums > Programming > Delete Last line of a text file

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

Delete Last line of a text file

Reply to Message Icon

Name: b1pal
Date: October 22, 2009 at 12:45:18 Pacific
OS: Windows XP
Subcategory: Batch
Comment:

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



Sponsored Link
Ads by Google

Response Number 1
Name: IVO
Date: October 22, 2009 at 14:00:38 Pacific
Reply:

@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
)


0

Response Number 2
Name: ghostdog
Date: October 22, 2009 at 20:25:53 Pacific
Reply:

@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


0

Response Number 3
Name: IVO
Date: October 23, 2009 at 02:43:18 Pacific
Reply:

@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.


0

Response Number 4
Name: b1pal
Date: October 23, 2009 at 07:41:54 Pacific
Reply:

it works! thanks


0

Response Number 5
Name: FishMonger
Date: October 23, 2009 at 08:04:56 Pacific
Reply:

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


0

Related Posts

See More



Sponsored Link
Ads by Google
Reply to Message Icon





Use following form to reply to current message:

Login or Register to Reply
LoginRegister


Sponsored links

Ads by Google


Results for: Delete Last line of a text file

Delete blank lines from a text file www.computing.net/answers/programming/delete-blank-lines-from-a-text-file/14525.html

i wanted to delete the content of a text file www.computing.net/answers/programming/i-wanted-to-delete-the-content-of-a-text-file/19673.html

dos appending last line of text fil www.computing.net/answers/programming/dos-appending-last-line-of-text-fil/13113.html