如何根据行号删除(删除)文本文件的特定行?
问题描述:
我有一个简单的脚本,可以删除文本文件的前 n 行.
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"
iNumberOfLinesToDelete = 5
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 > (iNumberOfLinesToDelete - 1) Then
objTS.WriteLine arrLines(i)
End If
Next
我想问一下,如果你只想要删除文本文件中的特定行,是否有办法?含义基于文本文件的行号.
I would like to ask if there is a way if you only have a specific line in the text file which you only want to delete? Meaning based on the line number of the text file.
例如,
1
2
This is line 3
4
5
并且您想删除第 3 行.特别是第 3 行.
And you want to remove line number 3. Specifically line number 3.
结果:
1
2
4
5
有没有办法做到这一点?
Is there a way on how to do it?
非常感谢您的回答和帮助.
A big appreciation for the answer and the help.
答
感谢 Ekkehard.Horner 发现我的错误.
Thanks to Ekkehard.Horner for finding my error.
更新:
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