Powershell: Filter the contents of a file by an array of strings

后端 未结 4 1463
[愿得一人]
[愿得一人] 2021-02-05 08:27

Riddle me this:

I have a text file of data. I want to read it in, and only output lines that contain any string that is found in an array of search terms.

If I

相关标签:
4条回答
  • 2021-02-05 08:42

    without regex and with spaces possible:

    $array = @("foo", "bar", "hello world")
    get-content afile | where { foreach($item in $array) { $_.contains($item) } } > FilteredContent.txt
    
    0 讨论(0)
  • 2021-02-05 08:44

    Try Select-String . It allows an array of patterns. Ex:

    $p = @("this","is","a test")
    Get-Content '.\New Text Document.txt' | Select-String -Pattern $p -SimpleMatch | Set-Content FilteredContent.txt
    

    Notice that I use -SimpleMatch so that Select-String ignores special regex-characters. If you want regex in your patterns, just remove that.

    For a single pattern I would probably use this, but you have to escape regex characters in the pattern:

    Get-Content '.\New Text Document.txt' | ? { $_ -match "a test" }
    

    Select-String is a great cmdlet for single patterns too, it's just a few characters longer to write ^^

    0 讨论(0)
  • 2021-02-05 08:48
    $a = @("foo","bar","baz")
    findstr ($a -join " ") afile > FilteredContent.txt
    
    0 讨论(0)
  • 2021-02-05 08:56

    Any help?

    $a_Search = @(
        "TextI'mLookingFor",
        "OtherTextI'mLookingFor",
        "MoreTextI'mLookingFor"
        )
    
    
    [regex] $a_regex = ‘(‘ + (($a_Search |foreach {[regex]::escape($_)}) –join “|”) + ‘)’
    
    (get-content afile) -match $a_regex 
    
    0 讨论(0)
提交回复
热议问题