Search code examples
vbscriptlines

Delete preceding lines from text file if line has value


i have a text file with numbers and i must delete the lines before a given number.

45048 
67113.88 
74484 
597.6 
1945.65 
8714.5 
32085.9 
741.12 
1721.39 
35266.7 
8260.71 
23635.8 
40487.5 
40702.18 
29544.74 
110000 
810000 
3161000 
29201.91 
33000 

So i must delete the lines before number 110000 . Or in another day i must delete the lines before 1721.39. I don't know how to make the deletion before the user input value. or just delete first 25 line if user prompt 25...

Const ForReading = 1
Const ForWriting = 2

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\db\a.txt", ForReading)

strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, " ", "")

Set objFile = objFSO.OpenTextFile("C:\db\a.txt", ForWriting)
objFile.WriteLine strNewText

objFile.Close

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\db\a.txt", ForReading)

strText = objFile.ReadAll
objFile.Close

strNewText = Replace(strText, "forward", "")

Set objFile = objFSO.OpenTextFile("C:\db\a.txt", ForWriting)
objFile.WriteLine strNewText
objFile.Close

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\db\a.txt", ForReading)

strText = objFile.ReadAll
objFile.Close

strNewText = Replace(strText, ".", "")

Set objFile = objFSO.OpenTextFile("C:\db\a.txt", ForWriting)
objFile.WriteLine strNewText
objFile.Close

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\db\a.txt", ForReading)

strText = objFile.ReadAll
objFile.Close

strNewText = Replace(strText, " ", "")

Set objFile = objFSO.OpenTextFile("C:\db\a.txt", ForWriting)
objFile.WriteLine strNewText
objFile.Close

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\db\a.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:\db\a.txt", ForWriting)
objFile.Write strNewContents
objFile.Close

Solution

  • Try this for delete number of lines, And try yourself others.

    Const FOR_READING = 1 
    Const FOR_WRITING = 2 
    strFileName = "C:\txt.txt" 
    NumberOfLinesToBeDelete=inputbox("How many lines want to delete from beginning","Delete","")
    
    
    Set objFS = CreateObject("Scripting.FileSystemObject") 
    Set objTS = objFS.OpenTextFile(strFileName, FOR_READING) 
    strContents = objTS.ReadAll 
    objTS.Close 
    
    arrLines = Split(strContents, vbNewLine) 
    Set objTS = objFS.OpenTextFile(strFileName, FOR_WRITING) 
    
    For i=0 To UBound(arrLines) 
       If i > (NumberOfLinesToBeDelete - 1) Then 
          objTS.WriteLine arrLines(i) 
       End If 
    Next