Search code examples
powershellcsvtext-parsing

Powershell: Read Text file line by line and split on "|"


I am having trouble splitting a line into an array using the "|" in a text file and reassembling it in a certain order. There are multiple lines like the original line in the text file.

This is the original line:

80055555|Lastname|Firstname|AidYear|DCDOCS|D:\BDMS_UPLOAD\800123456_11-13-2018 14-35-53 PM_1.pdf

I need it to look this way:

80055555|DCDOCS|Lastname|Firstname|AidYear|D:\BDMS_UPLOAD\800123456_11-13-2018 14-35-53 PM_1.pdf

Here is the code I am working with:

$File = 'c:\Names\Complete\complete.txt'
$Arr = $File -split '|'
foreach ($line in Get-Content $File)
{
  $outputline = $Arr[0] + "|" + $Arr[4] + "|" + $Arr[1] + "|" + $Arr[2] + "|" + 
    "@@" + $Arr[5] |
      Out-File -filepath "C:\Names\Complete\index.txt" -Encoding "ascii" -append 
}

Solution

  • You need to process every line of the file on its own and then split them.

    $File = get-content "D:\test\1234.txt"
    foreach ($line in $File){
        $Arr = $line.Split('|')
        [array]$OutputFile +=  $Arr[0] + "|" + $Arr[4] + "|" + $Arr[1] + "|" + $Arr[2] + "|" + "@@" + $Arr[5] 
    }
    $OutputFile | out-file -filepath "D:\test\4321.txt" -Encoding "ascii" -append 
    

    edit: Thx to LotPings for this alternate suggestion based on -join and the avoidance of += to build the array (which is inefficient, because it rebuilds the array on every iteration):

    $File = get-content "D:\test\1234.txt"
    $OutputFile = foreach($line in $File){($line.split('|'))[0,4,1,2,3,5] -Join '|'}
    $OutputFile | out-file -filepath "D:\test\4321.txt" -Encoding "ascii"