简体   繁体   English

捕获并导出多个命名组到csv

[英]capture and export multiple named groups to csv

I'd like to capture two particular data from the input files using regular expressions like this: 我想使用正则表达式从输入文件中捕获两个特定的数据:

$reg = [regex]"(?<Name>^Name:.*)|(?<Id>^Id:.*)"
gci C:\test\*.txt | Get-Content | Select $reg -allmatches | Select -Expand Matches|
...
new-object psobject -property @{Name=$n; Id=$i}
...
Select-Object Name, Id | Export-Csv c:\info.csv –NoTypeInformation

The problem I faced is some files don't have 'Id' entry. 我遇到的问题是某些文件没有“ Id”条目。 If any file doesn't have the 'Id' entry in it, it doesn't show up in the exported csv file. 如果任何文件中没有“ Id”条目,则该文件不会显示在导出的csv文件中。 I'd greatly appreciate if someone could help me come up with the solution. 如果有人可以帮助我提出解决方案,我将不胜感激。

C:\\test\\file1.txt contains: C:\\test\\file1.txt包含:

Name: Sturgeon Ocean   
Alias: Socean   
Id: 384932   
Address: 3600 Caviar  
Street, Pacific beach   
...   
Cell: 389-394-3843   
...  

Not tested, but I think this should work: 未经测试,但我认为这应该工作:

Foreach ($file in gci C:\test\*.txt)
 { 
   $Record = New-object PSObject -Property @{Name=$null;ID=$null}
   Foreach ($line in Get-Content $file.FullName)
    {
      switch -Regex ($_)
      {
       '^Name' {$Record.Name = ($_ -replace '^Name:(.+)$','$1').Trim()}
       '^ID'   {$Record.ID   = ($_ -replace '^ID:(.+)$','$1').Trim()}
      }
    }
    $Record
 }

No switch 没有开关

$reg = [regex]"(^Name:.*)|(^Id:.*)"

gci c:\new*.txt | 
foreach {
          $matched = (gc reg_test0.txt) -match $reg -replace '^.+:\s*',''
           new-object psobject -Property @{Name=$matched[0];ID=$matched[1]} 
        }| Select Name,Id | Export-Csv c:\new\info.csv -NoTypeInformation

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM