简体   繁体   English

Powershell文本字符串转换为CSV

[英]Powershell text string to CSV

I initially thought this problem more complex than it actuially is but after digging around I still cant seem to find a solution that I can re-purpose. 最初,我认为这个问题比实际的更为复杂,但是在深入研究之后,我似乎仍然找不到能够重新利用的解决方案。 I'm trying to use wildcards but perhaps I'm going about this the wrong way 我正在尝试使用通配符,但也许我正在以错误的方式进行操作

I have a text file as below: 我有一个文本文件,如下所示:

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

I would like a single CSV with 2 columns such as: 我想要一个包含2列的CSV,例如:

EXTERNAL ID     M01

12345678-1      M07

18765432-1      M14

19638527-1      M14

17418529-1      M07

Any insight or help is appreciated 任何见解或帮助表示赞赏

Here is something that I think will do what I want. 这是我认为可以做的事情。 It could probably be made more efficient and smaller but I went for easy to read and comprehend instead: 它可能可以变得更高效,更小,但是我还是为了易于阅读和理解而去:

$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

Similar to EBGreen's answer, but simpler I think. 与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

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

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