How to delete (remove) a specific line of a text file based on the line number?

前端 未结 2 1997
温柔的废话
温柔的废话 2021-01-14 10:00

I have a simple script that deletes the first n lines of a text file.

Const FOR_READING = 1 
Const FOR_WRITING = 2 
strFileName = \"C:\\scripts\\test.txt\"          


        
相关标签:
2条回答
  • 2021-01-14 10:20

    Just to show @Thomas (and others) that the condition should be

    If UBound(Filter(arrSkipLines, i) = -1 Then ' i not found in array/Filter returns empty array
    
    
    >> WScript.Echo UBound(Filter(Array(1,2,3),2))
    >>
    0
    >> WScript.Echo UBound(Filter(Array(1,2,3),4))
    >>
    -1
    
    0 讨论(0)
  • 2021-01-14 10:44

    Thanks to Ekkehard.Horner for finding my error.

    Update:

    Const FOR_READING = 1 
    Const FOR_WRITING = 2 
    strFileName = "C:\scripts\test.txt" 
    
    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 ShouldSkip(i) Then 
          objTS.WriteLine arrLines(i) 
       End If 
    Next 
    
    Function ShouldSkip(i)
        Dim arrSkipLines, x
        arrSkipLines = Array(1, 22, 32, 42, 169)
        For Each x In arrSkipLines
            If x = i Then
                ShouldSkip = True
                Exit Function
            End If
        Next
    
        ShouldSkip = False
    End Function
    
    0 讨论(0)
提交回复
热议问题