使用 Powershell 在文件中查找多行模式 [英] Using Powershell to find multi-line patterns in files

查看:40
本文介绍了使用 Powershell 在文件中查找多行模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 Powershell 在文件中找到多行模式,例如 XML 节点的内容?

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

即如果我在 deviceDescription 节点中查找单词green",但 XML 节点文本可能跨越多行,这不起作用:

i.e. if I were looking for the word "green" within the deviceDescription node, but the XML node text may span multiple lines, this doesn't work:

dir -r -i *.xml | select-string -Pattern "<deviceDescription>.*green.*</deviceDescription>"

推荐答案

首先,如果是 xml,则提取设备描述字符串进行处理,然后匹配您想要的字符串,在本例中为绿色.

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"

如果您不想那样做,则必须使用 ?s - 使 * 匹配换行符的单行或 dotall 标志:

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>"

请注意,您可能想要使用 .*? 或者这可能跨越多个 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.

这篇关于使用 Powershell 在文件中查找多行模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆