如何在VBS中的特定文本下方写入第n行

How to write nth line below specific text in VBS

在一个由数千条记录组成的文本文件中,每条记录都超过 20 行数据,如果第 14 行为空白,我需要计算每条记录开始后的第 14 行。该行为空白或包含日期。

每条记录的开头相同:“1 条新记录的开头”

场景:

1 新记录开始
2 一些数据
3"
4"
5"
6"
7"
8"
9"
10“
11"
12"
13"
14
...
1 新记录开始
...
8"
9"
10"
...
14 2019 年 10 月 19 日
...

在这个简单的场景中,结果应该是 1。我有代码将每条记录的第 1 行复制到第二个文件中。

结果显然是:

1 新记录开始
1 新记录开始
...

这是我的代码:

Const ForReading = 1

Dim words(1)

Dim msg

words(0) = "1  Start of New Record"

Set objFSO = CreateObject("Scripting.FileSystemObject")

Set inFile = objFSO.OpenTextFile("c:\Temp\altest.txt", ForReading)

Set outFile = objFSO.OpenTextFile("c:\Temp\altest_output.txt", 8, True)

Do Until inFile.AtEndOfStream

    strSearchString = inFile.ReadLine

    For i = 0 To UBound(words)-1

    If InStr(strSearchString,words(i)) Then

   msg = msg&strSearchString&vbcrlf

    End If

    next

Loop

inFile.Close

outfile.WriteLine msg

WScript.Echo "Done!"

这似乎是一个好的开始,但同样,如果第 14 行是空白,我需要计算每条记录开始后的第 14 行。

非常感谢任何帮助。 -阿莱尔

算不上优雅,但像这样的东西应该会让你上路。这不使用 SkipLine,它只是标记下一个感兴趣的行:

Option Explicit 'force explicit variable declaration, this is just good practice

Const ForReading = 1

Dim strContent
Dim Offset : Offset = 14 'define the 14th 'line'
Dim StartLine

Dim NewRecordMarker : NewRecordMarker = "1 Start of new record" 'just use a string to match

Dim objFSO, inFile, outFile
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set inFile = objFSO.OpenTextFile("e:\Temp\altest.txt", ForReading)
Set outFile = objFSO.OpenTextFile("e:\Temp\altest_output.txt", 8, True)

'notice we're only reading forward
'that means we can set the next LineOfInterest without having to worry about
'exceeding AtEndOfStream like we would if we'd use SkipLine
'this is just simpler.
'this obviously falls apart when the line of interest is NOT the 14th line
Do Until inFile.AtEndOfStream
    Dim LineOfInterest
    strContent = inFile.ReadLine 'inFile.Line will at 2 at this point because we just read it

    If strContent = NewRecordMarker Then 'found a new record, we want to look 14 lines from here
        LineOfInterest = inFile.line - 1 + Offset ' -1 or we'll overshoot our target
    End If

    If inFile.Line = LineOfInterest Then 'this is the line we want to inspect
        outFile.WriteLine strContent 'just write out entire value, no checking for date here
    End If
Loop

inFile.Close
outFile.Close

WScript.Echo "Done!"