Search code examples
powershellheadermultiple-columnstxt

I need to change the order and values of columns of a .txt file without any headers


I have a IExport.txt file with one or more lines of numbers and letters separated by semicolon and a total of 14 columns.
The file has no headers and i need it to be like this

4;1613000026438;T0011368;1.00;715004978;922105;;101120;;171;Name0;Thing1;Name1;989105

This is what i imagine the file to look like (part of it):

H1 H2            H3       H4   H5        H6     H7    H8
-- ------------- -------- ---- --------- ------ ----- ---
4  1613000026438 T0011368 1.00 715004978 922105

I need to change the file as follows:
Column 7 to 14 shall be deleted
Value "1.00" in column 4 shall be set to "1"
And the columns shall be reordered like this:

H1 H3       H4 H2            H5        H6
-- -------- -- ------------- --------- ------
4  T0011368 1  1613000026438 715004978 922105

I need the file in the end like this:

4;T0011368;1;1613000026438;715004978;922105

I want to change the file as stated above, but without any headers and rename it from "IExport.txt" to "KExport.txt".
Is there a way to reorder the columns without naming them?

I have edited my question, because i understand i didn't provide enough information and because i don't need the headers anymore.

I would very much appreciate your help.


Solution

  • As in this case you want an output file without quotes or header, you can use Import-Csv to read and parse the input file and then output a series of chosen items joined with ; in the order you need

    Try:

    $fileIn = 'X:\Somewhere\IExport.txt'
    $result = Import-Csv -Path $fileIn -Delimiter ';' -Header (1..6 | ForEach-Object { "H$_" }) |
              ForEach-Object {
                 # reorder the fields, use [int] on H4 and output a semi-colon delimited string
                 $_.H1, $_.H3, [int]$_.H4, $_.H2, $_.H5, $_.H6 -join ';'
             }
    # output the new file
    $fileOut = $fileIn -replace 'IExport\.txt$', 'XExport.txt'
    $result | Set-Content -Path $fileOut
    

    Result using your example:

    4;T0011368;1;1613000026438;715004978;922105