【发布时间】:2015-06-10 15:04:25
【问题描述】:
我正在尝试从文本文件中提取特定的行块,其中包含如下内容:
...
sCountry = "USA"
sCity = "New York"
sState = "New York"
...
sCountry = "USA"
sCity = "Los Angeles"
sState = "California"
这三行在整个文本文件中重复;我只想提取那些文本行,并将数据字段放入 csv 中,这样我就有了类似
"USA","New York","New York"
"USA","Los Angeles","California"
...
到目前为止,我有这个:
$inputPath = 'C:\folder\file.vbs'
$outputFile = 'C:\folder\extracted_data.csv'
$fileContent = [io.file]::ReadAllText($inputPath)
$regex = '(?sm)(s[A-Z][a-z]+ = "\w*"(\s*$)){3}'
$fileContent = $fileContent | Select-String $regex -AllMatches | % {$_.Matches} | % {$_.Value}
$fileContent = [regex]::Replace($fileContent, 'sCountry = ', '')
$fileContent = [regex]::Replace($fileContent, '(?sm)((^\s*)s[A-Z][a-z]+ = )', ',')
$fileContent > $outputFile
通过查看这个我能够获得:
Multiline regex to match config block.
但是,当我运行脚本时,我的输出文件是空的。它不会与我提供的 $regex 模式进行模式匹配,但如果我执行以下操作,它将在一行上匹配:
$regex = '(?sm)(sCountry = "\w*"(\s*$))'
但如果我做类似的事情就不会:
$regex = '(?sm)(s[A-Z][a-z]+ = "\w*"(\s*$))'
如何使模式匹配跨多行工作?
【问题讨论】:
-
你用的是什么版本的powershell?
-
@mjolinor,Windows PowerShell ISE,3.0,非 (x86)
标签: regex powershell