Convert fixed width txt file to CSV / set-content or out-file -append?

前端 未结 3 1187
长情又很酷
长情又很酷 2020-12-18 11:22

Input file is a fixed-width txt file. My client normally opens it in Excel and manually specifies the column breaks. I\'m hoping to replace certain blank spaces with a comma

3条回答
  •  梦毁少年i
    2020-12-18 12:14

    I would think this comes up a lot. Here's an example that actually goes overboard and turns the fixed width file into objects. Then it's simple to export that to a csv. This should work for converting legacy commands like netstat as well.

    $cols = 0,19,38,59,81,97,120,123 # fake extra column at the end, assumes all rows are that wide, padded with spaces
    $colsfile = 'columns.txt'
    $csvfile = 'cust.csv'
    
    $firstline = get-content $colsfile | select -first 1
    $headers = for ($i = 0; $i -lt $cols.count - 1; $i++) {
      $firstline.substring($cols[$i], $cols[$i+1]-$cols[$i]).trim()
    }
    
    # string Substring(int startIndex, int length)                                                                                         
    
    Get-Content $colsfile | select -skip 1 | ForEach {
      $hash = [ordered]@{}
      for ($i = 0; $i -lt $headers.length; $i++) {
        $value = $_.substring($cols[$i], $cols[$i+1]-$cols[$i]).trim()
        $hash += @{$headers[$i] = $value}
      }
      [pscustomobject]$hash
    } | export-csv $csvfile
    

提交回复
热议问题