Member Avatar for Member #1111627

Hi all,

I would like to replace new lines with "<BR>" in a text file. I'm executing the following line in Powershell:

[regex]::Replace((Get-Content "testfile.txt"), "\.``n", ".<BR>", "Singleline")

The contents of testfile.txt:

Some text here for paragraph one.

More text for paragraph two.

Dani AI

Generated

Short, practical fix and why it happened

As noticed, the confusing part is PowerShell's escape character: the backtick (`). That interacts badly with regex escape sequences unless you use the right string quoting. Also remember that plain Get-Content (without -Raw) returns an array of lines — for a regex replace on the whole file you want one string.

Recommended (PowerShell 3+)

$text = Get-Content -Raw -Encoding UTF8 "testfile.txt"
$text = $text -replace '\r?\n', '<BR>'
Set-Content -Encoding UTF8 "testfile_out.txt" -Value $text

Notes: use single quotes around the regex so PowerShell doesn't try to interpret backtick escapes. The pattern '\r?\n' matches both CRLF and LF line endings. Use -Raw so you operate on the whole file as one string.

If you must support older PowerShell (no -Raw)

$text = [System.IO.File]::ReadAllText("testfile.txt")
$text = $text -replace '\r?\n', '<BR>'
[System.IO.File]::WriteAllText("testfile_out.txt", $text, [System.Text.Encoding]::UTF8)

Extra tips

  • If you want paragraph semantics instead of lots of <BR>, replace double-newlines first (e.g. '\r?\n\s*\r?\n') with paragraph tags, then convert the remaining single newlines to <BR>.
  • Watch file encoding and final newline: Set-Content/WriteAllText let you control encoding.
  • If you still see surprises, print the raw bytes or open the file in a hex/UTF view to confirm whether line endings are CRLF, LF, or mixed.

This approach avoids backtick/string-escaping pitfalls and cleanly handles Windows and Unix line endings.

Member Avatar for Member #1111627

Had to make it \r`\n` when in the powershell script. Stupid backtick issue in the format, but basically \r\n.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.