How to use powershell to reorder CSV columns

后端 未结 5 2075
感动是毒
感动是毒 2020-12-05 19:54

Input file:

column1;column2;column3
data1a;data2a;data3a
data1b;data2b;data3b

Goal: output file with reordered columns, say



        
5条回答
  •  醉话见心
    2020-12-05 20:23

    It's great that people came with their solutions based on pure .NET. However, I would fight for the simplicity, if possible. That's why I upvoted all of you ;)

    Why? I tried to generate 1.000.000 records and store it in CSV and then reorder the columns. Generating the csv was in my case much more demanding then the reordering. Look at the results.

    It took only 1,8 minute to reorder the columns. For me it's pretty decent result. Is it ok for me? -> Yes, I don't need to try to find out quicker solution, it's good enough -> saved my time for some other interesting stuff ;)

    # generate some csv; objects have several properties
    measure-command { 
        1..1mb | 
        % { 
            $date = get-date
            New-Object PsObject -Property @{
                Column1=$date
                Column2=$_
                Column3=$date.Ticks/$_ 
                Hour = $date.Hour
                Minute = $date.Minute
                Second = $date.Second
                ReadableTime = $date.ToLongTimeString()
                ReadableDate = $date.ToLongDateString()
            }} | 
        Export-Csv d:\temp\exported.csv 
    }
    
    TotalMinutes      : 6,100025295
    
    # reorder the columns
    measure-command { 
        Import-Csv d:\temp\exported.csv | 
            Select ReadableTime, ReadableDate, Hour, Minute, Second, Column1, Column2, Column3 | 
            Export-Csv d:\temp\exported2.csv 
    }
    
    TotalMinutes      : 2,33151559833333
    

提交回复
热议问题