Extract substrings where match is found

时间:2015-07-28 15:43:06

标签: string powershell search substring powershell-v3.0

I have a text file with a number of lines. I would like to search each line individually for a particular pattern and, if that pattern is found output a substring at a particular position relative to where the pattern was found.

i.e. if a line contains the pattern at position 20, I would like to output the substring that begins at position 25 on the same line and lasts for five characters.

The following code will output every line that contains the pattern:

select-string -path C:\Scripts\trimatrima\DEBUG.txt -pattern $PATTERN 

Where do I go from here?

2 个答案:

答案 0 :(得分:0)

You can use the $Matches automatic variable:

Last match is stored in $Matches[0], but you can also use named capture groups, like this:

"test","fest","blah" |ForEach-Object {
    if($_ -match "^[bf](?<groupName>es|la).$"){
        $Matches["groupName"]
    }
}

returns es (from "fest") and la (from "blah")

答案 1 :(得分:0)

Couple of options.

Keeping Select-String, you'll want to use the .line property to get your substrings:

select-string -path C:\Scripts\trimatrima\DEBUG.txt -pattern $PATTERN |
 foreach { $_.line.Substring(19,5) }

For large files, Get-Content with -ReadCount and -match may be faster:

Get-Content C:\Scripts\trimatrima\DEBUG.txt-ReadCount 1000 |
 foreach {
  $_ -match $pattern |
  foreach { $_.substring(19,5) }
  }