[英]Search for RegEx string in files and return ONLY file name, path and string
我有點搜索引擎正則表達式字符串。 場景如下:
這是我到目前為止的內容:
$files = gci f:\beta\ -Include "*.tlt" -Recurse
$results = $files |
Select-String -Pattern 'Revision:.+.{1}[.]\d{1,3}'|
ForEach-Object { $_.Matches } |
select Value |
Format-Table -GroupBy Filename
我需要的是一個PowerShell腳本,該腳本可搜索文件並返回具有完整路徑的文件列表,並且僅包含修訂版1.234,而不是整行。
您已經很親密,但不可避免地需要遍歷文件。 注意-Filter
比-Include
快得多,因為它不會在過濾之前收集每個對象。
$fileList = Get-ChildItem -Path F:\beta -Filter *.tlt -Recurse
$results = foreach ($file in $fileList)
{
$find = $file | Select-String -Pattern '(Revision:.+?\.\d{1,3})'
if ($find)
{
@{
Path = $file.FullName
Rev = $find.Matches.Groups[0].Value
}
}
}
借助計算出的屬性,可以實現單管道解決方案:
Get-ChildItem f:\beta -Filter *.tlt -Recurse |
Select-String -List -Pattern 'Revision:.+?\.\d{3}' |
Select-Object @{ n='FullName'; e='Path' }, @{ n='Revision'; e={ $_.Matches.Value } }
樣本輸出:
FullName Revision
-------- --------
/Users/jdoe/foo.tlt Revision: 1.234
/Users/jdoe/sub/bar.tlt Revision: 10.235
正如提到TheIncorrigible1的答案 ,使用-Filter
執行比使用好得多-Include
,因為-Filter
在源過濾器(讓文件系統提供商做過濾),而不是收集所有文件的信息對象,然后再讓PowerShell的執行篩選。
Select-String -List
將每個輸入文件中的匹配限制為第一個匹配。
由每個輸出匹配Select-String
是[Microsoft.PowerShell.Commands.MatchInfo]
實例,它包含關於每個匹配豐富的元數據,如.Path
與全部輸入文件名,和.Matches
用約正則表達式什么信息( -Pattern
)匹配-該元數據用於通過上述計算出的屬性填充Select-Object
創建的輸出自定義對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.