Reputation: 13057
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
Output File
Upvotes: 0
Views: 582
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