Using Powershell to find multi-line patterns in files

后端 未结 1 593
温柔的废话
温柔的废话 2021-01-18 05:32

How would I find a multiline pattern in files, such as the contents of an XML node, using Powershell?

i.e. if I were looking for the word \"green\" within the

相关标签:
1条回答
  • 2021-01-18 06:11

    First of all, if is xml, extract the device description string treating it as such and then match for the string you want, in this case, green.

    $x = [xml] (gc .\test.xml)
    $x.deviceDescription -match "green"
    

    If you don't want to go that way, you will have to use the ?s - singleline or dotall flag which makes * match newlines:

    $x = [IO.File]::ReadAllText("C:\test.xml")
    $x -match "(?s)<deviceDescription>.*green.*</deviceDescription>"
    

    Note that you probably want to use .*? or this may span across multiple deviceDescription tags. Edge cases like this are reasons why you should avoid using regex for such things.

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