PowerShell正则表达式导出匹配内容

时间:2015-05-07 06:39:40

标签: regex powershell

我正在学习正则表达式,并试图通过使用值为100,000美元的文本文件来更好地理解它。我想要做的是在文本文件中搜索字符串" $ 100,000"如果是,那么将值导出到新的CSV中。这是我到目前为止所使用的。

      [io.file]::readalltext("c:\utilities\notes_$datetime.txt") -match("[$][0-9][0-9][0-9],[0-9][0-9][0-9]") | Out-File C:\utilities\amount.txt -Encoding ascii -Force

返回true。有人能指出我正确的方向,抓住它找到的新值的字符串值吗?

非常感谢!

3 个答案:

答案 0 :(得分:1)

您正在将文件读取为单个字符串,而不是行数组,因此您应该使用Select-String -AllMatches而不是-match运算符:

[IO.File]::ReadAllText("c:\utilities\notes_$datetime.txt") |
  Select-String '\$\d{3},\d{3}' -AllMatches |
  % { $_.Matches.Groups.Value } |
  Out-File C:\utilities\amount.txt -Encoding ascii -Force

作为旁注,使用Get-Content -Raw比使用.Net方法略微更多PoSh,尽管.Net方法提供了更好的性能。

Get-Content "c:\utilities\notes_$datetime.txt" -Raw |
  Select-String '\$\d{3},\d{3}' -AllMatches |
  % { $_.Matches.Groups.Value } |
  Out-File C:\utilities\amount.txt -Encoding ascii -Force

答案 1 :(得分:0)

我更喜欢使用 [regex] :: match

$x = 'text bla $100,000 text text'
[regex]::Match($x,"\$[\d]{3},[\d]{3}").Groups[0].Value

我也稍微改变了表达式($后跟3个数字,然后是“,”和另外3个数字)。

所以你的脚本看起来像这样:

$fileContent = Get-Content "c:\utilities\notes_$datetime.txt"    
[regex]::Match($fileContent,"\$[\d]{3},[\d]{3}").Groups[0].Value | Out-File C:\utilities\amount.txt -Encoding ascii -Force

答案 2 :(得分:0)

为什么不使用Select-String cmdlet - 更容易:

Select-String .\infile.csv -pattern '\$[\d]{3},[\d]{3}' | Select Line | Out-File outfile.txt

然后您可以像这样处理多个文件:

Get-Childitem *.csv | Select-String -pattern '\$[\d]{3},[\d]{3}' | Select Line | Out-File outfile.txt

Select-String具有以下属性:

行 - 正则表达式找到匹配的行

LineNumber - 找到匹配项的文件中的行号

文件名 - 在

中找到匹配项的文件名