PowerShell equivalent to grep -f

前端 未结 9 1610
情书的邮戳
情书的邮戳 2020-12-22 16:09

I\'m looking for the PowerShell equivalent to grep --file=filename. If you don\'t know grep, filename is a text file where each line has a regular

相关标签:
9条回答
  • 2020-12-22 16:29

    but select-String doesn't seem to have this option.

    Correct. PowerShell is not a clone of *nix shells' toolset.

    However it is not hard to build something like it yourself:

    $regexes = Get-Content RegexFile.txt | 
               Foreach-Object { new-object System.Text.RegularExpressions.Regex $_ }
    
    $fileList | Get-Content | Where-Object {
      foreach ($r in $regexes) {
        if ($r.IsMatch($_)) {
          $true
          break
        }
      }
      $false
    }
    
    0 讨论(0)
  • 2020-12-22 16:30

    The -Pattern parameter in Select-String supports an array of patterns. So the one you're looking for is:

    Get-Content .\doc.txt | Select-String -Pattern (Get-Content .\regex.txt)
    

    This searches through the textfile doc.txt by using every regex(one per line) in regex.txt

    0 讨论(0)
  • 2020-12-22 16:30

    I find out a possible method by "filter" and "alias" of PowerShell, when you want use grep in pipeline output(grep file should be similar):

    first define a filter:

    filter Filter-Object ([string]$pattern)
    {
        Out-String -InputObject $_ -Stream | Select-String -Pattern "$pattern"
    }
    

    then define alias:

    New-Alias -Name grep -Value Filter-Object
    

    final, put the former filter and alias in your profile:

    $Home[My ]Documents\PowerShell\Microsoft.PowerShell_profile.ps1

    Restart your PS, you can use it:

    alias | grep 'grep'

    ==================================================================

    relevent Reference

    1. alias: Set-Aliasenter link description here New-Aliasenter link description here

    2. Filter(Special function)enter link description here

    3. Profiles(just like .bashrc for bash):enter link description here

    4. out-string(this is the key)enter link description here:in PowerShell Output is object-basedenter link description here,so the key is convert object to string and grep the string.

    5. Select-Stringenter link description here:Finds text in strings and files

    0 讨论(0)
提交回复
热议问题