(I have read the other threads with similar names...)
I'm new to PowerShell. I am trying to understand how to find and replace newlines. For example, find double newlines and replace them with a single or vice versa.
I have a test document that was created using Notepad:
The quick brown fox jumped over the lazy dog
The quick brown fox jumped over the lazy dog
The quick brown fox jumped over the lazy dog
The quick brown fox jumped over the lazy dog
I am working in the PowerShell ISE for testing/learning.
When I run the following command (attempting to replace one newline with two):
((Get-Content -path $filename -raw) -replace '`n','`n`n') | Set-Content -path $filename
Get-Content -path $filename -raw
The output is unchanged. So I tried the following and it remained unchanged.
((Get-Content -path $filename -raw) -replace '`r`n','`r`n`r`n') | Set-Content -path $filename
So, knowing that PowerShell uses a back-tick rather than a backslash, but out of frustration, I tried the following command:
((Get-Content -path $filename -raw) -replace '\n','\n\n') | Set-Content -path $filename
And, surprisingly (to me), all of the newlines were replaced, but with the string literal '\n\n'. So it seems searching for a newline worked with a backslash but not with a back-tick. The replacement, unfortunately, was the literal string rather than the CRLF I need.
I'm stumped. But for what it's worth, I also tried the following and the string literal was again used for the replacement (i.e., in place of newlines, the document contained '`r`n').
((Get-Content -path $filename -raw) -replace '\n','`r`n') | Set-Content -path $filename
I have seen many posts where people were mistakenly using a backslash, but in my case it seems like a backslash is required for the search, and I don't understand what is required to replace a newline.
Thanks!
"`r`n"'`n'just matches the literal characters [backtick][n], which isn't what you want. You want to interpolate those values. For that, you'll need to use double quotes i.e.,'`n'should be"`n".'\n'was able to successfully match the newlines is because the-replaceoperator uses regular expression for the matching and\nis regex for newline. If you want to do a replace without matching based on regex, you can use the.replace()method instead.