How to get the captured groups from Select-String?

前端 未结 5 757
清酒与你
清酒与你 2020-12-05 16:41

I\'m trying to extract text from a set of files on Windows using the Powershell (version 4):

PS > Select-String -AllMatches -Pattern 

        
5条回答
  •  有刺的猬
    2020-12-05 17:41

    This script will grab a regex's specified capture group from a file's content and output its matches to console.


    $file is the file you want to load
    $cg is capture group you want to grab
    $regex is the regular expression pattern



    Example file and its content to load:

    C:\some\file.txt

    This is the especially special text in the file.



    Example Use: .\get_regex_capture.ps1 -file "C:\some\file.txt" -cg 1 -regex '\b(special\W\w+)'

    Output: special text


    get_regex_capture.ps1

    Param(
        $file=$file,
        [int]$cg=[int]$cg,
        $regex=$regex
    )
    [int]$capture_group = $cg
    $file_content = [string]::Join("`r`n", (Get-Content -Raw "$file"));
    Select-String -InputObject $file_content -Pattern $regex -AllMatches | % { $_.Matches.Captures } | % { echo $_.Groups[$capture_group].Value }
    

提交回复
热议问题