【问题标题】:Remove lines based upon string根据字符串删除行
【发布时间】:2016-07-16 17:28:39
【问题描述】:

我有一个错误日志文件,想要从中复制所有与设置的错误字符串不匹配的行。所以基本上我正在建立一个单独的未识别错​​误文件。

我定义了所有已知的错误类型

# Define all the error types that we need to search on 
$error_1 = "Start Date must be between 1995 and 9999"
$error_2 = "SYSTEM.CONTACT_TYPE"
$error_3 = "DuplicateExternalSystemIdException"
$error_4 = "From date after To date in address"
$error_5 = "Missing coded entry  for provider type category record"

这就是我在文件中读取的内容

(Get-Content $path\temp_report.log) |
    Where-Object { $_ -notmatch $error_1 } |
    Out-File $path\uncategorised_errors.log
(Get-Content $path\temp_report.log) |
    Where-Object { $_ -notmatch $error_2 } |
    Out-File $path\uncategorised_errors.log
(Get-Content $path\temp_report.log) |
    Where-Object { $_ -notmatch $error_3 } |
    Out-File $path\uncategorised_errors.log

我的输入文件是这样的:

2016 年 7 月 15 日 20:02:11,340 ExternalSystemId 不能与现有提供程序相同
2016 年 7 月 15 日 20:02:11,340
2016 年 7 月 15 日 20:02:11,340 ZZZZZZZZZZZZZZZZZZZZZZZZ
2016 年 7 月 15 日 20:02:11,340 DuplicateExternalSystemIdException
2016 年 7 月 15 日 20:02:11,340 DuplicateExternalSystemIdException
2016 年 7 月 15 日 20:02:11,340 SYSTEM.CONTACT_TYPE

当我应该只有 3 行时,我的输出完全相同:

2016 年 7 月 15 日 20:02:11,340 ExternalSystemId 不能与现有提供程序相同
2016 年 7 月 15 日 20:02:11,340
2016 年 7 月 15 日 20:02:11,340 ZZZZZZZZZZZZZZZZZZZZZZZZ

【问题讨论】:

    标签: powershell lines


    【解决方案1】:

    试试看:

    (Get-Content $path\temp_report.log) | Where-Object { $_ -notmatch $error_1 -and $_ -notmatch $error_2 -and $_ -notmatch $error_3 -and $_ -notmatch $error_4 -and $_ -notmatch $error_5} | Out-File $path\uncategorised_errors.log
    

    【讨论】:

    • 完美运行。我刚刚得到了这项工作,但你的答案更优雅,只是一个班轮。 $result = 获取内容 $path\temp_report.log $result | Where-Object {$_ -notmatch [regex]::escape($error_1)} |设置内容 $path\uncategorised_errors.log
    【解决方案2】:

    将已知错误设为数组,使用Select-String

    $errors=@(
        "Start Date must be between 1995 and 9999",
        "SYSTEM.CONTACT_TYPE",
        "DuplicateExternalSystemIdException",
        "From date after To date in address",
        "Missing coded entry  for provider type category record"
    )
    
    Select-String -Path D:\log.txt -NotMatch -Pattern $errors
    

    【讨论】:

    • 我会添加 -SimpleMatch 以避免过滤器字符串中的特殊字符导致意外结果。
    猜你喜欢
    • 2021-07-04
    • 1970-01-01
    • 2023-04-09
    • 2016-11-17
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    • 2022-01-01
    • 1970-01-01
    相关资源
    最近更新 更多