You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何根据行号删除文本文件中的指定行?

Hey Alex, let's fix up your VBScript so it correctly deletes those specific lines from your text file. There are two key issues in your current code that are preventing it from working as expected:

  1. Reversed Logic: Your loop is writing lines when ShouldSkip(i) returns True, which means you're keeping the lines you want to delete instead of skipping them.
  2. Line Number Mismatch: The array of lines from Split uses 0-based indexing (first line is index 0), but your arrSkipLines uses 1-based line numbers (first line is 1). This means you're targeting the wrong lines entirely.

Here's the corrected script with those issues fixed, plus a few extra improvements for edge cases:

Const FOR_READING = 1
Const FOR_WRITING = 2
strFileName = "\\jarvisfs1\groups\InforIFC\Licence_BOB\NEW\test3.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)
    ' Only write lines that we DON'T want to skip
    If Not ShouldSkip(i) Then
        ' Avoid writing an empty line if the file ended with a newline
        If arrLines(i) <> "" Then
            objTS.WriteLine arrLines(i)
        End If
    End If
Next
objTS.Close ' Ensure the file is properly saved and released

Function ShouldSkip(i)
    Dim arrSkipLines, x
    ' These are 1-based line numbers (matching what you'd see in a text editor)
    arrSkipLines = Array(1, 22, 32, 42, 169)
    For Each x In arrSkipLines
        ' Convert 1-based line number to 0-based array index
        If (x - 1) = i Then
            ShouldSkip = True
            Exit Function
        End If
    Next
    ShouldSkip = False
End Function

Key Fixes Explained:

  • Reversed Condition: Changed If ShouldSkip(i) Then to If Not ShouldSkip(i) Then so we only write lines that aren't marked for deletion.
  • 0-Based Index Adjustment: Added x - 1 in the function to align your 1-based line numbers with the array's 0-based indices.
  • Empty Line Handling: Added a check to avoid writing an extra empty line if your original file ended with a newline (a common edge case when using Split with vbNewLine).
  • File Closure: Added objTS.Close after writing to make sure the file is properly saved and system resources are released.

This script will now read your file, exclude the lines specified in arrSkipLines, and write the remaining lines back to the original file. Just double-check you have write permissions for the file path you're using!

内容的提问来源于stack exchange,提问作者Alex Allen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:27:57