Home > Back-end >  I need to change the order and values of columns of a .txt file without any headers
I need to change the order and values of columns of a .txt file without any headers

Time:11-27

I have a IExport.txt file with one or more lines of numbers and letters separated by semicolon. The file has no headers. "4;1613000026438;T0011368;1.00;715004978;922105;;101120;;171;Name0;Thing1;Name1;989105"

I need to take the values of specific columns and change the order like the following: Some columns are deleted, some are re-ordered and one value is changed from "1.00" to "1". "4;T0011368;1;16130000026438;715004978;922105;;"

I want to import the file, change it and then export it with a different name (IExport.txt => KExport.txt)

I tried to using the following:

Import-CSV "IExport.txt" -Header 1, 2, 3, 4, 5, 6 | Export-CSV "KExport.txt" -NoTypeInformation

This will add headers to the file, but the first header (1) is the header for the complete line of values and not only for the value "4" as intended.

I would very much appreciate your help.

CodePudding user response:

'Dilly B', as per my comment, here's what I mean.

'John919', is this what you are after?

Clear-Host
'4;1613000026438;T0011368;1.00;715004978;922105;;101120;;171;Name0;Thing1;Name1;989105' | 
ConvertFrom-Csv -Delimiter ';' -header H1, H2, H3, H4, H5, H6 | 
# Results
<#
H1 : 4
H2 : 1613000026438
H3 : T0011368
H4 : 1.00
H5 : 715004978
H6 : 922105
#>
Select-Object -Property @{
    Name       = 'Row'
    Expression = {$PSItem.H1} 
}, H3, @{
    Name       = 'H4'
    Expression = {($PSItem.H4) -replace '\.\d '} 
}, H2, H5, H6 | 
# Results
<#
Row : 4
H3  : T0011368
H4  : 1
H2  : 1613000026438
H5  : 715004978
H6  : 922105
#>
Format-Table -AutoSize
# Results
<#
Row H3       H4 H2            H5        H6    
--- --       -- --            --        --    
4   T0011368 1  1613000026438 715004978 922105
#>

Of course 'John919', other than the Format-Table things, you can just do what you say you are after.

Export-csv -Path "$env:USERPROFILE\Documents\KExport.txt" -NoTypeInformation
Import-Csv -Path "$env:USERPROFILE\Documents\KExport.txt"

Yet, as you can see, one can do this on the fly and manipulate it further as one chooses, without the need to serialize the results to the file system.

CodePudding user response:

By using semicolon as delimiter you could do it.

Import-Csv -Path C:\temp\sample.txt -Header 1,2,3,4,5,6 -Delimiter ';'

Export it as a csv and import again with your desired order like 1,3,6,2,5,4

  • Related