Remove lines based upon string

…衆ロ難τιáo~ 提交于 2020-01-25 13:05:08

问题


I have an error log file from which want to copy all lines that DON'T match a set error strings. So basically I am building up a separate file of unrecognised errors.

I define all the know error types

# 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"

and this is what I am doing to read in the file

(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

My input file is like this:

15 Jul 2016 20:02:11,340 ExternalSystemId cannot be the same as an existing provider
15 Jul 2016 20:02:11,340 XXXXXXXXXXXXXXXXXXXXXXXXX
15 Jul 2016 20:02:11,340 ZZZZZZZZZZZZZZZZZZZZZZZZ
15 Jul 2016 20:02:11,340 DuplicateExternalSystemIdException
15 Jul 2016 20:02:11,340 DuplicateExternalSystemIdException
15 Jul 2016 20:02:11,340 SYSTEM.CONTACT_TYPE

and my out is exactly the same when I should have only 3 lines:

15 Jul 2016 20:02:11,340 ExternalSystemId cannot be the same as an existing provider
15 Jul 2016 20:02:11,340 XXXXXXXXXXXXXXXXXXXXXXXXX
15 Jul 2016 20:02:11,340 ZZZZZZZZZZZZZZZZZZZZZZZZ

回答1:


try it:

(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



回答2:


Make the known errors an array, use 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


来源:https://stackoverflow.com/questions/38405279/remove-lines-based-upon-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!