簡體   English   中英

我如何在目錄中的文本文件中搜索多個字符串模式

[英]How can i search for multiple string patterns in text files within a directory

我有一個接受輸入並搜索驅動器的文本框。

例如驅動器是 C:/users/me

假設我在那里有多個文件和子目錄,我想搜索文件中是否存在以下字符串:“ssn”和“DOB”

一旦用戶輸入兩個字符串。 我將字符串拆分為空格,這樣我就可以遍歷數組。 但這是我當前的代碼,但我仍然堅持如何進行。

  gci "C:\Users\me" -Recurse | where { ($_ | Select-String -pattern ('SSN') -SimpleMatch) -or ($_ | Select-String -pattern ('DOB') -SimpleMatch ) } | ft CreationTime, Name -Wrap -GroupBy Directory | Out-String

如果我手動將上面的代碼粘貼到 powershell 中,上面的代碼就可以工作,但我試圖在腳本中重新創建它,但對如何操作感到困惑。

下面的這段代碼沒有得到所有需要的文件。

foreach ($x in $StringArrayInputs) {
           if($x -eq $lastItem){
                $whereClause = ($_  | Select-String -Pattern $x)
            }else{
                $whereClause = ($_ | Select-String -Pattern $x) + '-or'
            } 
            $files= gci $dv -Recurse | Where { $_ | Select-String -Pattern $x -SimpleMatch} | ft CreationTime, Name -Wrap -GroupBy Directory | Out-String
}

Select-String-Pattern參數接受一個字符串數組(其中任何一個都會觸發匹配),因此直接管道到單個Select-String調用應該這樣做:

$files= Get-ChildItem -File -Recurse $dv | 
          Select-String -List -SimpleMatch -Pattern $StringArrayInputs } |
            Get-Item |
              Format-Table CreationTime, Name -Wrap -GroupBy Directory |               
                Out-String

筆記:

  • -FileGet-ChildItem一起使用使其僅返回文件,而不返回目錄。

  • -ListSelect-String結合使用是一種優化,可確保每個文件最多查找並報告一個匹配項。

  • Select-String的 output 傳遞給Get-Item會自動將前者的 output 的.Path屬性綁定到后者的-Path參數。

    • 嚴格來說,綁定到-Path會使參數解釋為通配符表達式,但是,這通常不是問題 - 除非路徑包含[字符。
    • 如果可能的話,插入一個帶有Select-Object @{ Name='LiteralPath'; Expression='Path' }的管道段。 Select-Object @{ Name='LiteralPath'; Expression='Path' }Get-Item之前,這確保綁定到-LiteralPath

我只是按照您的示例並將兩者與正則表達式結合起來。 我轉義了正則表達式以避免意外使用表達式(例如任何字符的點)。

它適用於我的測試文件,但可能與您的文件不同。 您可能需要使用適當的編碼添加“-Encoding UTF8”,以便您也可以獲得區域特定的字符。

$String = Read-Host "Enter multiple strings seperated by space to search for"
$escapedRegex = ([Regex]::Escape($String)) -replace "\\ ","|"

Get-ChildItem -Recurse -Attributes !Directory | Where-Object {
    $_ | Get-Content | Select-String -Pattern $escapedRegex
} | Format-Table CreationTime, Name -Wrap -GroupBy Directory | Out-String

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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