删除基于字符串的行
问题描述:
我有一个错误日志文件,想要复制所有不匹配设置错误字符串的行。所以基本上我正在建立一个无法识别错误的单独文件。删除基于字符串的行
我定义所有知道的错误类型
# 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
我输入文件什么是这样的:
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
和我出门的时候完全一样,我应该只有3条线:
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
答
尝试:
(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
答
充分利用已知错误的阵列,完全使用Select-String
[email protected](
"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
+0
我会添加'-SimpleMatch'来避免过滤器字符串中特殊字符的意外结果。 –
作品。我刚刚获得这项工作,但你的答案更优雅,只是一个班轮。 $ result = Get-Content $ path \ temp_report.log $ result | Where-Object {$ _ -notmatch [regex] :: escape($ error_1)} | Set-Content $ path \ uncategorised_errors.log – zoomzoomvince