Monday, March 18, 2019

Create Pipe-Delimited File from Fixed-Width File

<# SPECIFY INPUT FILE NAME #>
$file = "FULL_PATH_TO_FIXED_WIDTH_FILE"


<# SPECIFY INPUT FILE NAME #>
$outputFileName = "FULL_PATH_TO_PIPE_DELIMITED_FILE"



$count = 0
$instream = New-Object System.IO.StreamReader($file)
$outstream = New-Object System.IO.StreamWriter($outputFileName, 0)      <# create new file #>

<# write out columns names in the first row #>
$outstream.WriteLine("<< PIPE DELIMITED LIST OF FIELD NAMES FOR 1ST ROW >>")


while (($line = $instream.ReadLine()) -ne $null)         
        {
            $SYS_ID = $line.Substring(30, 1)
            if ($SYS_ID -eq "K" -or $SYS_ID -eq "L") {

                <#  add $line.Substring(OFFSET, LENGTH)  for each field to extract #>
                $out = $line.Substring(0, 44) + "|" + `
$line.Substring(0, 2) + "|" + `
$line.Substring(2, 2) + "|" + `
$line.Substring(4, 2) + "|" + `
$line.Substring(6, 8) + "|" + `
$line.Substring(14, 9) + "|" + `
$line.Substring(23, 1) + "|" + `
$line.Substring(24, 6) + "|" + `
$line.Substring(30, 1) + "|" + `
$line.Substring(31, 9) + "|" + `
$line.Substring(40, 2) + "|" + `
$line.Substring(44, 5) + "|" + `
$line.Substring(89, 8) + "|" + `
$line.Substring(102, 10) + "|" + `
$line.Substring(112, 10) + "|" + `
$line.Substring(122, 10) + "|" + `
$line.Substring(132, 2) + "|" + `
$line.Substring(174, 12) + "|" + `
$line.Substring(195, 4) + "|" + `
$line.Substring(228, 4) + "|" + `
$line.Substring(228, 4) + "|" + `
$line.Substring(296, 10) + "|" + `
$line.Substring(436, 9) + "|" + `
$line.Substring(524, 4) + "|" + `
$line.Substring(528, 8) + "|" + `
$line.Substring(528, 8) + "|" + `
$line.Substring(536, 8) + "|" + `
$line.Substring(544, 8) + "|" + `
$line.Substring(560, 8) + "|" + `
$line.Substring(568, 8) + "|" + `
$line.Substring(585, 69) + "|" + `
$line.Substring(710, 1) + "|" + `
$line.Substring(891, 4) + "|" + `
$line.Substring(953, 8) + "|" + `
$line.Substring(961, 1) + "|" + `
$line.Substring(978, 40) + "|" + `
$line.Substring(1078, 11) + "|" + `
$line.Substring(1089, 11) + "|" + `
$line.Substring(2865, 2) + "|" + `
$line.Substring(2867, 8) + "|" + `
$line.Substring(2875, 8)


$outStream.WriteLine($out)
                $count = $count + 1
            }
        }
$instream.Close();
$outstream.Close();

No comments:

Post a Comment