0

I have a PowerShell program to replace some strings with another from an input file but the output file has an extra space/line when compared to input file.

$InputACKFile = 'C:\Testing_Newline\Aj*.dat'

Write-Host "Found " ($InputACKFile | Measure-Object).Count " files to process"

$InputACKFile = Get-ChildItem $InputACKFile

foreach ($xfile in $InputACKFile) {
    Write-Host "Processing file: $xFile`r"

    #((Get-Content $xfile).Replace("~", "`n")) | Out-File $xfile.FullName
    [System.IO.File]::ReadAllText($xfile).Replace("~","`n") |
        Set-Content $xfile

    $flag = 0
    (Get-Content $xfile | ForEach {
        if ($_ -match "^PQ\*") {
            $_ -replace "test1", "test2"
        } elseif ($_ -match "^TA\*") {
            $_ -replace "test1", "test2"
        } elseif ($_ -match "^ABC\*RS\*") {
            $_ = '';
            $flag = 1
        } elseif ($_ -match "^(DE\*)([0-9]+)(\*[0-9]+)$" -and $flag -eq 1) {
            $_ -replace ($matches[2]), ([int]::Parse($matches[2])-1);
            $flag = 0
        } else{
            $_
        }
    }) | Out-File $xfile.FullName -Encoding Ascii

    ((Get-Content $xfile) -join("~")) | Set-Content $xfile.FullName
}
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • 5
    If your question is about a trailing newline being added to the output file: that's how `Set-Content` works. If you want to avoid that use `[IO.File]::WriteAllText()` instead. – Ansgar Wiechers Oct 09 '18 at 11:05
  • 3
    You might want to move your `"Found X files to process"` line below `Get-ChildItem` as at the moment it will only ever return '1 file' because you're measuring a string. – henrycarteruk Oct 09 '18 at 11:14
  • You could spare the first elseif using an **OR**ed RegEx `if ($_ -match "^PQ\*|^TA\*") {` –  Oct 09 '18 at 11:29
  • 2
    depending on how many if clauses you have here you might consider using a `switch -regex` instead – Matt Oct 09 '18 at 11:33

0 Answers0