2

In Powershell I'm trying to replace the following:

<Name>RANDOMTEXT</Name>
</Member>

With

<Name>RANDOMTEXT</Name></Member>

I'm using the following code:

$content = [System.IO.File]::ReadAllText(<XMLFILE>).Replace("</Name>`n</Member>","</Name></Member>")
[System.IO.File]::WriteAllText(<NEWFILE>, $content)

The replace is not working.

Is there any way to do this?

1
  • 1
    Try .Replace("</Name>`r`n</Member>","</Name></Member>") Commented Jan 3, 2017 at 19:36

2 Answers 2

4

I recommend using RegEx replace (the -replace operator) as opposed to the static string (method) version, if you want to be able to handle both Windows and Unix style newlines.

Windows style is carriage return followed by linefeed (2 characters, CRLF or "`r`n"), Unix style is just linefeed (LF or "`n")

Using regex replace:

$content = [System.IO.File]::ReadAllText(<XMLFILE>) -replace '</Name>\r?\n</Member>','</Name></Member>'

Or replacing all newlines:

$content = [System.IO.File]::ReadAllText(<XMLFILE>) -replace '\r?\n'

The question mark ? makes the CR optional (match 0 or 1), so this will encompass all newlines.

Sign up to request clarification or add additional context in comments.

Comments

1

Try .Replace("</Name>" + [Environment]::NewLine + "</Member>","</Name></Member>")

or .Replace("</Name>`r`n</Member>","</Name></Member>")

On a General note, if all you want to do is to remove the new lines, you can simply try [System.IO.File]::ReadAllText(<XMLFILE>).Replace([Environment]::NewLine,"")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.