簡體   English   中英

在文件中搜索RegEx字符串,僅返回文件名,路徑和字符串

[英]Search for RegEx string in files and return ONLY file name, path and string

我有點搜索引擎正則表達式字符串。 場景如下:

  • 我有一堆帶有隨機內容的某些擴展名(* .tlt)的文件
  • 所有文件都位於驅動器F上的BETA文件夾的子文件夾中:
  • 每個文件在內容中的某處至少具有一個修訂版1.234 (有時會多次-僅首次出現很重要)

這是我到目前為止的內容:

$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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM