如何根据行号删除(删除)文本文件的特定行? [英] How to delete (remove) a specific line of a text file based on the line number?

查看:57
本文介绍了如何根据行号删除(删除)文本文件的特定行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的脚本,可以删除文本文件的前 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

这篇关于如何根据行号删除(删除)文本文件的特定行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆