Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to read a CSV file and output a CSV file with only one (1) field. I have tried to create a concise example.

PS C:srcpowershell> Get-Content ..csv
field1,field2,field3
1,2,3
4,55,6
7,888,9

PS C:srcpowershell> Import-Csv -Path ..csv | `
>>     ForEach-Object {
>> $_.field2 `
>>     } | `
>>     Export-Csv -Path .x.csv -NoTypeInformation
>>

The problem is that the Length of field2 is written to the exported CSV file. I want the field header to be "field2" and the values to be the value from the original CSV file. Also, I only want quotes where they are required; not everywhere.

I have read Export-CSV exports length but not name and Export to CSV only returning string length. But these do not seem to address producing an actual CSV file with a header and one field value.

PS C:srcpowershell> get-content .x.csv
"Length"
"1"
"2"
"3"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.8k views
Welcome To Ask or Share your Answers For Others

1 Answer

CSV object uses note properties in each row to store its fields so we'll need to filter each row object and leave just the field(s) we want using Select-Object cmdlet (alias: select), which processes the entire CSV object at once:

Import-Csv 1.csv | select field2 | Export-Csv 2.csv -NoTypeInformation

Note, there's no need to escape the end of line if it ends with |, {, (, or ,.
It's possible to specify several fields: select field2, field3.


To strip unneeded doublequotes, general multi-field case:

Import-Csv 1.csv |
    select field2 |
    %{
        $_.PSObject.Properties | %{ $_.value = $_.value -replace '"', [char]1 }
        $_
    } |
    ConvertTo-Csv -NoTypeInformation |
    %{ $_ -replace '"(S*?)"', '$1' -replace 'x01', '""' } |
    Out-File 2.csv -Encoding ascii

Simplified one-field case:

Import-Csv 1.csv |
    select field2 |
    %{
        $_.field2 = $_.field2 -replace '"', [char]1
        $_
    } |
    ConvertTo-Csv -NoTypeInformation |
    %{ $_ -replace '"(S*?)"', '$1' -replace 'x01', '""' } |
    Out-File 2.csv -Encoding ascii

A tricky case of embedded quotes inside a field was solved by temporary replacing them with a control character code 01 (there are just a few that can be used in a typical non-broken text file: 09/tab, 0A/line feed, 0D/carriage return).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...