Ramil
Ramil

Reputation: 87

Powershell Replace two empty lines with one

I have text files that are generated with 2 empty lines between each block of text. I could use Notepad++ to do this using replace \r\n\r\n with \r\n, but there has to be a way to do this automatically.

I've tried to come up with something in Powershell, but nothing has worked so far.

This is what I've tried so far:

(Get-Content .\test.txt).Replace("\n\n",'\n') | Set-Content .\test.txt
(Get-Content .\test.txt).Replace("\s+\r\n+",'\r\n') | Set-Content .\test.txt
(Get-Content .\test.txt).Replace("\r\n+",'') | Set-Content .\test.txt
(Get-Content .\test.txt).Replace("\n+",'') | Set-Content .\test.txt
(Get-Content .\test.txt).Replace("\r\n\r\n",'\r\n') | Set-Content .\test.txt
(Get-Content .\test.txt).Replace("^(\s+\r\n)",'\r\n') | Set-Content .\test.txt
(Get-Content .\test.txt).Replace("^(\s+\r\n+)",'\r\n') | Set-Content .\test.txt
(Get-Content .\test.txt).Replace("^(\r\n+)",'\r\n') | Set-Content .\test.txt
(Get-Content .\test.txt).Replace("\r\n",'\b') | Set-Content .\test.txt

Upvotes: 4

Views: 2827

Answers (2)

iTayb
iTayb

Reputation: 12743

Get-Content returns a list of strings, and not a whole piece of text, like you need. Ovbiously you meant running this Replace method on a string, and not on a list of strings.

Use Get-Content -Raw .\test.txt to load the file content as one long string.

Also, the correct form of the replacement would be:

Replace("`r`n`r`n", "`r`n")

To sum up:

(Get-Content -Raw .\test.txt).Replace("`r`n`r`n", "`r`n") | Set-Content .\test.txt

Will do the job.

Another approach would be to just filter out empty lines:

$data = Get-Content .\test.txt
$data | Where-Object { $_ } | Set-Content .\test.txt

Upvotes: 6

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174445

PowerShell uses backticks ` not backslashes \ to escape special characters:

(Get-Content .\test.txt) -replace "(`r?`n){2}",$([Environment]::Newline) | Set-Content .\test.txt

Using the regex -replace operator with a conditional carriage return will match any type of newline.

Upvotes: 4

Related Questions