Powershell文本字符串为CSV

时间:2014-08-13 14:48:34

标签: string powershell csv wildcard

我最初认为这个问题比它本身更复杂但是在挖掘之后我仍然无法找到一个我可以重新使用的解决方案。我试图使用通配符,但也许我会以错误的方式解决这个问题

我有一个文本文件如下:

SQL*Plus: Release 11.2.0.1.0 Production on Wed Aug 13 14:20:22 2014
Copyright (c) 1982, 2010, Oracle.  All rights reserved.
Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
With the Partitioning, Real Application Clusters, Automatic Storage Management, OLAP,
Data Mining and Real Application Testing options

EXTERNAL ID

--------------------------------------------------------------------------------

'M1

---


12345678-1

M07


18765432-1

M14

19638527-1

M14



EXTERNAL ID

--------------------------------------------------------------------------------

'M1

---


17418529-1

M07

我想要一个包含2列的CSV,例如:

EXTERNAL ID     M01

12345678-1      M07

18765432-1      M14

19638527-1      M14

17418529-1      M07

感谢任何见解或帮助

2 个答案:

答案 0 :(得分:0)

这是我认为会做我想要的事情。它可能会变得更有效率和更小,但我去了易于阅读和理解:

$res = @()
$content = get-content SomeFile.txt | ?{($_ -ne 'EXTERNAL ID') -AND (-NOT $_.StartsWith('"-')) -AND ($_ -ne "'M1") -AND (-NOT $_.Startswith('SQL*')) -AND ($_ -ne '')}

for($count = 0; $count -lt $content.Count; $count = $count + 2){
    $id = $content[$count]
    $m = $content[$count + 1]
    $temp = New-Object PSCustomObject -Property @{'External ID' = $id;
                                                  'M01' = $m;
    }
    $res += $temp
}
$res | Export-CSV .\Som\Path\Name.csv -NoTypeInformation

答案 1 :(得分:0)

与EBGreen的答案类似,但我认为更简单。

$Col2=$false
gc c:\temp\test.txt |Select -skip 6| ?{![string]::IsNullOrEmpty($_) -and $_ -notmatch "^(---|External|'M1)"} | %{
    If($Col2){
        [PSCustomObject][Ordered]@{
            'External ID'=$Col1
            "'M1"=$_}
        $Col2=$false
        }else{
            $Col1=$_
            $Col2=$true
        }
    } | Export-Csv C:\temp\New.csv -NoTypeInformation