首次出现关键字后的特定行

时间:2014-06-24 14:39:14

标签: vbscript

我有一个文件,我可以在其中找到使用vbscript的关键字,但我需要继续复制下面的3-4行,直到我发现另一个类似的关键字模式。 我写过类似的东西 - (我是新手,因为我很愚蠢)

Set fso = CreateObject("Scripting.FileSystemObject")
Set inFile  = fso.OpenTextFile("FileName", 1)
Set outFile = fso.OpenTextFile("FileName", 8, True)
outFile.WriteLine("This is some sample data.")
strAnswer = InputBox("Please enter a value:", _
    "Enter Value")
Do until inFile.AtEndOfStream
  line = inFile.ReadLine
  If InStr(line, strAnswer) Then
    outFile.WriteLine line ' Copy the line and write to output file
    serNum = Left(line, 7)
    'If Not ((line = inFile.ReadLine())
    'take first 3 char and find the next occurance of it
    'copy all lines until that line
    WScript.Echo "Found"
  End If        
Loop
outfile.Close
Set fSO = Nothing

任何建议都值得赞赏。

2 个答案:

答案 0 :(得分:0)

您可以使用子循环继续写入,直到再次找到序列号。

Do until inFile.AtEndOfStream
    line = inFile.ReadLine
    If InStr(line, strAnswer) Then
        outFile.WriteLine line ' Copy the line and write to output file
        serNum = Left(line, 7)

        ' Continue writing until EOF or serial number is found...
        Do While Not inFile.AtEndOfStream
            line = inFile.ReadLine
            If InStr(line, serNum) = 0 Then outFile.WriteLine line
        Loop

    End If        
Loop

答案 1 :(得分:0)

使用变量serNum的状态来决定当前行需要做什么:

Do until inFile.AtEndOfStream
  line = inFile.ReadLine

  If Not IsEmpty(serNum) And InStr(line, serNum) > 0 Then WScript.Quit
  If IsEmpty(serNum) And InStr(line, strAnswer) > 0 Then serNum = Left(line, 7)
  If Not IsEmpty(serNum) Then outFile.WriteLine line
Loop
  • 第一个条件检查您是否找到了第二个匹配,然后退出。
  • 第二个条件检查您是否找到了第一个匹配项,然后初始化serNum
  • 第三个条件导致第一个匹配的所有行到第二个匹配之前的行都被写入输出文件。