删除匹配字符串之间的多行

时间:2015-09-28 06:07:13

标签: windows vbscript scripting

我编写一个脚本来删除文件中两个匹配字符串之间的多行。

代码编写如下,但执行后删除完整的行。任何人都可以建议我如何实现这个?

Const ForReading = 1
Const ForWriting = 2

count = 0

strFileName = Wscript.Arguments(0)

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strFileName, ForReading)

Do Until objFile.AtEndOfStream
    strLine = objFile.ReadLine

    flag = 0
    If InStr(strLine, "BBB") = 0 Then
        flag = 1
    End If

    If flag = 1 Then
        Exit Do
    End If

    If count = 1 Then
        If flag = 0 Then
            'strNewContents = strNewContents & strLine & vbCrLf
        End If
    End If

    If InStr(strLine, "GGG") = 0 Then
            strLine = ""
            'strNewContents = strNewContents & strLine & vbCrLf
            count = 1
    End If
Loop

objFile.Close

Set objFile = objFSO.OpenTextFile(strFileName, ForWriting)
objFile.Write strNewContents

objFile.Close
}

文件包含如下

AAA
BBB
CCC
DDD
EEE
FFF
GGG
HHH
III
JJJ

我希望输出为

AAA 
HHH
III 
JJJ

1 个答案:

答案 0 :(得分:0)

以下几行会导致您的脚本在遇到包含" BBB"的行而不是时立即从循环中退出,从而为您留下一个空变量strNewContents

If InStr(strLine, "BBB") = 0 Then
    flag = 1
End If

If flag = 1 Then
    Exit Do
End If

您实际想要做的是在循环外初始化您的标志变量,并在遇到符合条件的字符串时切换它:

skip = False
Do Until objFile.AtEndOfStream
    strLine = objFile.ReadLine

    If InStr(strLine, "BBB") > 0 Then skip = True
    If Not skip Then
        If IsEmpty(strNewContents) Then
            strNewContents = strLine
        Else
            strNewContents = strNewContents & vbNewLine & strLine
        End If
    End If
    If InStr(strLine, "GGG") > 0 Then skip = False
Loop