我有一个看起来像这样的文件:
Alpha,25,SomeBrand,Info
Gamma,2039,Crisps,Foobar
Epic,240,Win,Post
我想清除这个文件中的某一行,比如第2行,所以它看起来像这样:
Alpha,25,SomeBrand,Info
Epic,240,Win,Post
我怎样才能有效地做到这一点?这个文件有超过18000行,我已经尝试在完整的文件中读取并回写,但它太慢了。
答案 0 :(得分:0)
由于您无法使用文件指针移动技巧来更改VBScript中的“磁盘上”文件,因此您必须重新编写它。您是否测试过使用.ReadAll()和.Write是否“足够快”?如果是,我们可以讨论一种有效修改的方法。第一个问题:您是要删除违规行,还是应该替换为空行?
下一步:
此VBScript代码:
Dim goFS : Set goFS = CreateObject( "Scripting.FileSystemObject" )
Dim sDir : sDir = "..\testdata\editlargefile"
Dim sSrcFSpec : sSrcFSpec = goFS.BuildPath( sDir, "lines.txt" )
Dim nLine : nLine = 5
Dim nSize : nSize = goFS.GetFile( sSrcFSpec ).Size
WScript.Echo nSize, "bytes in", sSrcFSpec
ReDim aHead( nLine - 2 )
Dim oTS, nIdx, sTail
Set oTS = goFS.OpenTextFile( sSrcFSpec )
For nidx = 0 To UBound( aHead )
aHead( nIdx ) = oTS.ReadLine()
Next
oTS.ReadLine
sTail = oTS.ReadAll()
oTS.Close
WScript.Echo Left( Join( aHead, vbCrLf ) & vbCrLf & vbCrLf & Left( sTail, 100 ), 150 )
Set oTS = goFS.CreateTextFile( sSrcFSpec, True )
oTS.Write Join( aHead, vbCrLf )
oTS.Write vbCrLf & vbCrLf
oTS.Write sTail
oTS.Close
输出:
20888896 bytes in ..\testdata\editlargefile\lines.txt
This is line 1
This is line 2
This is line 3
This is line 4
This is line 6
This is line 7
This is line 8
This is line 9
This is line 10
Thi
=====================================================
xplfs.vbs: Erfolgreich beendet. (0) [11.42188 secs]
演示了我能想到的最快的VBScript方式。伪代码 对于能够做文件指针技巧的语言将是
Open the file in read+write mode
Loop over the head lines to keep
If Delete
Skip line to delete
Reset write file pointer to end of previous line
Block write to file pointer till end
Else
Fill line to delete with spaces
End
Close the file
您打算使用哪种语言?
答案 1 :(得分:0)
我不知道你的文件大小是多少,但我写了一个脚本(asp)在2.5秒内执行。
文本文件大小为3500万字节,有35,000行。
下面:
<%@Language = VBScript %>
<%
Option Explicit
Dim oFso, oFile, arrLns, arrLNums, strOut, e
arrLNums = Array(15) '15th [and nnth] line(s) will be cleared
Set oFso = CreateObject("Scripting.FileSystemObject")
Set oFile = oFso.OpenTextFile("C:\old.txt", 1)
strOut = Replace(oFile.ReadAll(), vbCr, "")
arrLns = Split(strOut, vbLf)
For Each e In arrLNums : arrLns(e - 1) = "" : Next
strOut = Join(arrLns, vbCrLf)
oFso.CreateTextFile("C:\cleared.txt", True)_
.Write(strOut) 'Saved
oFile.Close
Set oFile = Nothing
Set oFso = Nothing
%>