-1

I am trying to modify an HTML file using Powershell, but replacing [DISPLAY_NAME] is not possible because of the [ and ] symbols.

(Get-Content ".\hi4.htm") -replace '[DISPLAY_NAME]', 'tulpa' | Set-Content '.\hi4.htm'

But output looks like the following. Please check and help.

<httulpatulpa>
<botulpatulpa>
<ttulpabtulpatulpa tulpattulpatulpatulpa="wtulpatulpath: 579tulpax;" bortulpatulpar="5" ctulpatulpatulpatulpatulpatulpactulpatulpag="0" ctulpatulpatulpatulpatulpatulpatulpatulpatulpag="0">
<tbotulpatulpa>
<tr>
<ttulpa tulpattulpatulpatulpa="fotulpat-ftulpatulpatulpatulpatulpa: Htulpatulpavtulpattulpactulpa, tulpartulpatulpatulpa, tulpatulpatulpatulpa-tulpatulpartulpaf; fotulpat-tulpatulpaztulpa: 18tulpax; wtulpatulpath: 577tulpax;" htulpatulpaght="64"><tulpatrotulpag>  [tulpatulpatulpatulpatulpatulpatulpatulpatulpatulpatulpatulpa] </tulpatrotulpag>&tulpabtulpatulpa;<tulpatulpag tulpattulpatulpatulpa="fot
codewario
  • 19,553
  • 20
  • 90
  • 159
  • If you're literally replacing `'[DISPLAY_NAME]'`, you can do it with a string replace. You don't need regex to replcae a literal string. – erik258 Oct 29 '19 at 17:06
  • 2
    escape the brackets with backslash... e.g: `-replace '\[DISPLAY_NAME\]'` – Avshalom Oct 29 '19 at 17:07
  • Instead of using the regex-enabled `-replace` operator, consider using the non-regex-enabled [`.replace()` method](https://learn.microsoft.com/en-us/dotnet/api/system.string.replace?view=netframework-4.8). – Jeff Zeitlin Oct 29 '19 at 17:12
  • This is XML or HTML. Don't parse it with a regex. Use a dedicated parser. – Daniel Mann Oct 29 '19 at 17:28

2 Answers2

0

As the comments have indicated, there's no need to use the -replace operator (which uses the regex engine) for something as simple as this. Just use the normal String.Replace method.

(Get-Content ".\hi4.htm").Replace('[DISPLAY NAME]','tulpa') | Set-Content '.\hi4.htm'

If you insist on using regex, you need to escape the special characters in your string like this.

 (Get-Content ".\hi4.htm") -replace '\[DISPLAY_NAME\]', 'tulpa' | Set-Content '.\hi4.htm'
Ryan Bolger
  • 1,275
  • 8
  • 20
0

You absolutely can replace [DISPLAY_NAME], you just need to escape the [] when using the -replace operator. To use your provided code above, note the change below:

(Get-Content ".\hi4.htm") -replace '\[DISPLAY_NAME\]', 'tulpa' | Set-Content '.\hi4.htm'

You can also use the [string].Replace method as well, which does not use regex, just a string to look for to replace:

(Get-Content ".\hi4.htm").Replace('[DISPLAY_NAME]', 'tulpa') | Set-Content '.\hi4.htm'
codewario
  • 19,553
  • 20
  • 90
  • 159