我有一个文件input.txt
,其中包含如下文本:
GRP123456789
123456789012
GRP234567890
234567890123
GRP456789012
"A lot of text. More text. Blah blah blah: Foobar." (Source Error) (Blah blah blah)
GRP567890123
Source Error
GRP678901234
Source Error
GRP789012345
345678901234
456789012345
我试图捕获所有出现的“GRP ##########”,条件是下一行至少有一个数字。
因此,GRP123456789有效,但GRP456789012和GRP678901234无效。
我在http://regexstorm.net/tester上想到的RegEx模式是:
(GRP[0-9]{9})\s\n\s+[0-9]
到目前为止,基于该站点http://techtalk.gfi.com/windows-powershell-extracting-strings-using-regular-expressions/,我拥有的PowerShell脚本为:
$input_path = 'C:\Users\rtaite\Desktop\input.txt'
$output_file = 'C:\Users\rtaite\Desktop\output.txt'
$regex = '(GRP[0-9]{9})\s\n\s+[0-9]'
select-string -Path $input_path -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Values } > $output_file
我没有得到任何输出,也不确定为什么。
对此的任何帮助将不胜感激,因为我只是想更好地理解这一点。
最佳答案
您需要先将文本输入转换为单个字符串,然后再将其传递给Select-String
,否则该cmdlet将单独在每一行上操作,因此永远找不到匹配项。
Get-Content $input_path | Out-String |
Select-String $regex -AllMatches |
Select-Object -Expand Matches |
ForEach-Object { $_.Groups[1].Value } |
Set-Content $output_file
如果您使用的是PowerShell v3或更高版本,则可以将
Get-Content | Out-String
替换为Get-Content -Raw
。
关于regex - 打印Powershell Regex捕获到输出文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41109331/