【发布时间】:2017-10-28 03:02:56
【问题描述】:
我正在使用 powershell 搜索多个文件以查找与正则表达式的特定匹配。因为它是一个正则表达式,我不想只看到我编写的正则表达式接受的内容,以及匹配的行号。
然后我想获取匹配的值和行号并创建一个对象以输出到 excel 文件。
我可以在单独的选择字符串语句中获取每个项目,但是它们不会相互匹配
Select-String -Path $pathToFile -Pattern '(?<={\n\s*Box\s=\s")14\d{3}(?=",)' |
Select LineNumber, Matches.Value
#Will only print out the lineNumber
Select-String -Path $pathToFile -Pattern '(?<={\n\s*Box\s=\s")14\d{3}(?=",)' |
Foreach {$_.matches} | Select value
#Will only print matched value and can't print linenumber
谁能帮我获取行号和匹配值?
编辑:只是为了澄清我在做什么
$files = Get-ChildItem $directory -Include *.vb,*.cs -Recurse
$colMatchedFiles = @()
foreach ($file in $files) {
$fileContent = Select-String -Path $file -Pattern '(?<={\n\s*Box\s=\s")14\d{3}(?=",)' |
Select-Object LineNumber, @{Name="Match"; Expression={$_.Matches[0].Groups[1].Value}}
write-host $fileContent #just for checking if there is anything
}
这仍然没有得到任何东西,它只是输出了一堆空行
编辑:我期望这个脚本搜索目录中所有文件的内容并找到与正则表达式匹配的行。以下是我期望循环中每个文件的输出
LineNumber Match
---------- -----
324 15
582 118
603 139
... ...
文件匹配示例:
{
Box = "5015",
Description = "test box 1"
}....
{
Box = "5118",
Description = "test box 2"
}...
{
Box = "5139",
Description = "test box 3"
}...
【问题讨论】:
-
好的。现在:你想提取什么文本?
Box = "之后的数字? -
文件匹配示例上方的预期输出是我想要的。我想要箱号的最后 3 位数字。我不介意盒子号码的所有数字。我可以弄清楚正则表达式,它只是得到匹配的行号和匹配的值
-
好的,我们终于得到了你想要的。请参阅我的答案中的示例 2。
-
请参阅更新答案中的示例 3 - 仅输出匹配项,其中每个匹配项之前的行包含
{字符。经验教训:准确解释您希望正则表达式做什么。
标签: powershell