【问题标题】:delete multiple lines between matched strings删除匹配字符串之间的多行
【发布时间】:2015-12-25 07:38:54
【问题描述】:

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

代码编写如下,但执行后会删除完整的行。谁能建议我如何实现这一点?

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

【问题讨论】:

    标签: windows vbscript scripting


    【解决方案1】:

    以下行会导致您的脚本在遇到包含“BBB”的行not时立即退出循环,从而为您留下一个空变量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
    

    【讨论】:

    • 如果我正确地阅读了他的预期输出,我认为他希望 GGG 成为停止但仍将其排除的指标,因此对 skip = false 的检查应该在循环结束时,所以多一行被替换。
    猜你喜欢
    • 1970-01-01
    • 2010-12-25
    • 1970-01-01
    • 2022-10-15
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    相关资源
    最近更新 更多