-1

expire.txt文件包含197.015

foo1; 2020-03-01 13:33;
foo2; 2020-02-01 08:45;
foo3; 2020-01-01 11:30;
...
...
...

在这个大的 txt 文件中,我需要从以下位置替换所有日期值:

  1. 2020-03-01 13:332020-03-01
  2. 2020-02-01 08:452020-02-01
  3. 2020-01-01 11:302020-01-01
  4. ...
  5. ...
  6. 2018-01-01 12:402018-01-01(这是最后一行197.015

我已经尝试了下面的代码。

没有错误,但 txt 文件中的替换输入不起作用。

新的expire.txt文件保持不变。

如何解决这个问题?

Const ForReading = 1
Const ForWriting = 2
intCount = 0
intIndex = 1
Set oFSO = CreateObject("Scripting.FileSystemObject")
str_input = ""
Set oInFile = oFSO.OpenTextFile("expiration.txt", 1)
str_input = oInFile.ReadAll()
Set oRegEx = CreateObject("VBScript.RegExp")
With oRegEx
    .Multiline = True
    .Global = True
    .Pattern = "(\d+)-(\d+)-(\d+)\s(\d+):(\d+):(\d+);"
End With
Do Until oInFile.AtEndOfStream
str_input = oInFile.ReadLine
If (intCount = 0) Then
   str_input = oRegEx.Replace(str_input, "$1-$2-$3;")
   Set oInFile = oFSO.OpenTextFile("expiration.txt", 2)
   oInFile.Write str_input
   oInFile.Close
End If
intCount = intCount + 1
If (intCount = 200) Then
    intCount = 0
    intIndex = intIndex + 1
    oInFile.Close
End If
Loop
oInFile.Close
set oFSO = nothing
WScript.echo "ok"
4

1 回答 1

2

尝试从大型输入文件中读取每一行,处理该行,然后一次将其写入新的输出文件一行。如有必要,您可以删除原始输入文件,并在脚本末尾重命名新的输出文件(验证后)。

我在您当前的脚本中看到的一些问题:

  • 它同时调用ReadAll()and ReadLine(),这是不必要的。
  • 在再次打开同一个文件之前,它不会调用Close原始文件句柄。 ForReadingForWriting
  • 它只尝试翻译输入文件的第一行(以及随后的第 200 行),当intCount为 0(零)时。
  • 正则表达式期望列出秒,但您的示例YYYY-MM-DD hh:mm;日期时间数据不包含秒,因此正则表达式不匹配。

我不确定该intCount = 200块的目的是什么,所以我在回答中省略了它。无论如何,我保持行计数器intCount变量不变,以防您以后想使用它。

这是一个可能的修复...

Option Explicit

Const ForReading = 1

Dim oRegEx : Set oRegEx = New RegExp
oRegEx.Multiline = True
oRegEx.Global = True
oRegEx.Pattern = "(\d+)-(\d+)-(\d+)\s(\d+):(\d+);"

Dim intCount : intCount = 0
Dim str_input : str_input = ""
Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
Dim oInFile : Set oInFile = oFSO.OpenTextFile("expiration.txt", ForReading)
Dim oOutFile : Set oOutFile = oFSO.CreateTextFile("expiration~2.txt", True)
Do Until oInFile.AtEndOfStream
    str_input = oInFile.ReadLine()

    If oRegEx.Test(str_input) Then
        oOutFile.WriteLine oRegEx.Replace(str_input, "$1-$2-$3;")
    Else
        oOutFile.WriteLine str_input
    End If

    intCount = intCount + 1
Loop

oOutFile.Close
oInFile.Close

Set oOutFile = Nothing
Set oInFile = Nothing

' If necessary, use oFSO to delete the original expiration.txt file here, and rename expiration~2.txt to expiration.txt

Set oFSO = Nothing
Set oRegEx = Nothing

WScript.Echo "Ok"

希望这可以帮助。

于 2020-03-29T13:41:33.560 回答