UserX
UserX

Reputation: 13

Piping Replace to New File

$x = Get-Content($file)
if ($x -match("~")) {
  $x -replace("~","~`n") | Out-File $file
}

This is the snippet of code I am using. I have debugged up until this point and the code isn't updating after I replace the character tilda ~ with itself and then create a new line. When I output it to the command window and comment out the | Out-File $file the code works fine. When I try to pipe the new result back into the original file the code doesn't "unwrap" the file.

Upvotes: 0

Views: 66

Answers (2)

UserX
UserX

Reputation: 13

My mistake. I was calling reader method above.

ForEach ($file in $Path){
    $Array = @()
    $reader = new-object System.IO.StreamReader($file)

I needed an array to determine if the file needed to be unwrapped to begin with. If the contents took up 1 line it needed to be unwrapped. If not then it did not. I essentially used streamreader which is going to store each line as an element in an array. I forgot to close $reader before so we had a producer-consumer issue and thus Out-File could not override $file.

Fixed Snippet:

if($Array.length -eq 1){
        $x = Get-Content($file)

        if($x -match("~")){
            $reader.close()
            ($x -replace("~","~`n")) | Out-File $file
            }

        }

Upvotes: 0

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200323

The replacement works just fine. However, you're inserting just linefeed characters (LF, `n), not the combination of carriage-return and linefeed (CR-LF, `r`n) that Windows uses for encoding line breaks. Because of that you don't see line breaks when opening the file in Notepad. PowerShell accepts both LF and CR-LF as line break encoding, so you see correctly wrapped lines when you output the file there.

Change your code to this and you'll get the expected result:

(Get-Content $file) -replace '~', "~`r`n" | Set-Content $file

Upvotes: 2

Related Questions