mservidio
mservidio

Reputation: 13057

Powershell output file missing lines from input file

Why would the output file produced by the following script not contain all of the lines that were contained in the original file? I'm doing replacement logic on a line by line level, I'm not explicitely removing any lines though.

[regex]$r = "\$\%\$@@(.+)\$\%\$@@";

(Get-Content $inputFile) | 
    Foreach-Object {
        $line = $_;
        $find = $r.matches($line);

        if ($find[0].Success) {
            foreach ($match in $find) {
                $found = $match.value           
                $replace = $found -replace "[^A-Za-z0-9\s]", "";            
                $line.Replace($found, $replace);
            }       
        }
    } | 
Set-Content $outputFile

Input File

Input File

Output File

Output File

Upvotes: 0

Views: 582

Answers (1)

mjolinor
mjolinor

Reputation: 68243

You're only outputting content to the pipe if it finds a match, at this line:

$line.Replace($found, $replace)

If there was not a match found, then you need to output the line without doing any replacement:

[regex]$r = "\$\%\$@@(.+)\$\%\$@@";

(Get-Content $inputFile) | 
    Foreach-Object {
        $line = $_;
        $find = $r.matches($line);

        if ($find[0].Success) {
            foreach ($match in $find) {
                $found = $match.value           
                $replace = $found -replace "[^A-Za-z0-9\s]", "";            
                $line.Replace($found, $replace);
            }       
        }

        Else { $line }

    } | 
Set-Content $outputFile

Upvotes: 1

Related Questions