Extract multiple lines of text between two key words from shell command in powershell

后端 未结 2 2104
别那么骄傲
别那么骄傲 2020-12-22 03:22

I have a shell command I\'d like to extract data from using Powershell. The data I need will always sit between two key words and the number of lines captured can change. <

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-22 03:49

    Try this regex:

    $result = ($text | Select-String 'System1:\s*\r\n((.*\r\n)*)\s*System2:' -AllMatches)
    $result.Matches[0].Groups[1].Value
    

    Where $text is your original input. Note that you might have to adjust your line endings from \r\n to \n depending on your input. You may also have more than one match, I'm not sure from your sample.

    The regex starts matching with System1:\s*\r\n which is System1 followed by any number of spaces, followed by a newline. It ends the match with the literal System2:. The inner middle, .*\r\n, matches all characters followed by a newline. The outer middle (.*\r\n)* says to repeatedly match that pattern. Finally that construct is grouped, ((.*\r\n)*) so that all the matching lines can be extracted as the result.

提交回复
热议问题