Monday, April 25, 2011

How can I delete the last line of a text file using the command prompt?

I have a text file that I am importing into access table using command prompt. The problem is that this text file has a blank line as the last line. Can anyone provide me with a script that deletes my blank line at the end of file so as I can finalize my automation process. I am using Windows 2000 platform.

From stackoverflow
  • Here is a script that deletes blank lines from a text file. It is written for windows 2000.

    Const ForReading = 1
    Const ForWriting = 2
    
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFile = objFSO.OpenTextFile("C:\Scripts\Test.txt", ForReading)
    
    Do Until objFile.AtEndOfStream
        strLine = objFile.Readline
        strLine = Trim(strLine)
        If Len(strLine) > 0 Then
            strNewContents = strNewContents & strLine & vbCrLf
        End If
    Loop
    
    objFile.Close
    
    Set objFile = objFSO.OpenTextFile("C:\Scripts\Test.txt", ForWriting)
    objFile.Write strNewContents
    objFile.Close
    
    Haoest : come on now, don't you see this can be done in 1 line with the right tool?
    notandy : Yup, or you can simply use this script without an additional tool to worry about. Its old tech, but it works. He asked for win2k otherwise I would have used PowerShell.
    notandy : (get-content C:\File.txt) | where {$_ -ne ""} | out-file c:\file.txt
    Renze de Waal : 1. This script removes all blank lines, but the requirement was to only delete the last blank line. 2. This script also removes leading and trailing spaces. 3. This script loads the entire file into memory and performs a lot of string appends while building the result string.
  • This works using head

    head -n -1 input.txt > output.txt
    

    Unfortunately I think Windows doesn't come with that useful tool by default, but installing Cygwin gives you that and a lot of other stuff as well.

    jdigital : You might try looking here for Windows ports of Unix utilities: http://unxutils.sourceforge.net/
  •  sed '$d'
    

    deletes the last line, but is not in Windows 2000. Get the gnu utils to obtain a sed for Windows.

    On this site you will find a list of other sed commands to manipulate files.

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.