如何根据行号删除文本文件中的指定行?
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:
- Reversed Logic: Your loop is writing lines when
ShouldSkip(i)returnsTrue, which means you're keeping the lines you want to delete instead of skipping them. - Line Number Mismatch: The array of lines from
Splituses 0-based indexing (first line is index 0), but yourarrSkipLinesuses 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) ThentoIf Not ShouldSkip(i) Thenso we only write lines that aren't marked for deletion. - 0-Based Index Adjustment: Added
x - 1in 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
SplitwithvbNewLine). - File Closure: Added
objTS.Closeafter 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
相关产品推荐
相关产品推荐

