Powershell -如何找到并返回具有不同模式的文件的不同行?



我正在寻找一种方法来返回在不同的行上匹配不同模式的所有行。例如,第一行可能包含以下2个模式:25.2.2021 SET_ACCESS_GROUPS,另一行可能包含25.2.2021 DELETE_GROUP

我尝试了不同的东西,如以下,但它似乎没有找到任何匹配。

[String]$criteria1 = (25.2.2021+ ".*" + SET_ACCESS_GROUPS  + ".*")
[String]$criteria2 = (25.2.2021+ ".*" + DELETE_GROUP + ".*")
Get-Content $pathOrigin| Select-String -Pattern $criteria1,$criteria2| Set-Content $pathDestination

String方法:

[System.IO.File]::ReadAllLines($source) |
Where-Object { $_.StartsWith('25.2.2021') } | # This makes fast first-pass filter
Where-Object { $_.Contains('SET_ACCESS_GROUPS') -or $_.Contains('DELETE_GROUP') } | # Second-pass filter. Put strings in order how often they occured from often (leftmost) to rare (rightmost), this will speed up.
Out-File -FilePath $target

方法

[System.IO.File]::ReadAllLines($source) |
Where-Object { ($_ -like '25.2.2021*SET_ACCESS_GROUPS*') -or ($_ -like '25.2.2021*DELETE_GROUP*') } |
Out-File -FilePath $target

正则表达式方法:

[System.IO.File]::ReadAllLines($source) |
Where-Object { $_ -match '^25.2.2021.*(?:SET_ACCESS_GROUPS|DELETE_GROUP).*$' } |
Out-File -FilePath $target
<<p>RegEx对象/strong>方法:.
$regEx = [regex]::new('^25.2.2021.*(?:SET_ACCESS_GROUPS|DELETE_GROUP).*$', 
[System.Text.RegularExpressions.RegexOptions]::Singleline -bor 
[System.Text.RegularExpressions.RegexOptions]::IgnoreCase -bor 
[System.Text.RegularExpressions.RegexOptions]::Compiled )
[System.IO.File]::ReadAllLines($source) |
Where-Object { $regEx.IsMatch($_) } |
Out-File -FilePath $target

对于大量的数据,这些方法可能会有显著的性能差异。使用-cLike-cMatch进行区分大小写的搜索可能会更好,这样更快。RegEx方法通常是最慢的。RegEx Object方法优化为编译表达式一次。

最新更新