1

I am trying to replace a string in a file like this:

c:\>powershell -Command (gc D:\xxxxxxx\index.html) ^   
 -replace '^<script src="js/locale/languageholder.js"^>^</script^>', '' ^
| Out-File -encoding ASCII "D:\yyyyyyyyy\index.html"

the string I want to remove is:

<script src="js/locale/languageholder.js"></script>

no errors, but it is just not replaced. I assume there must be some charactors to be escaped, but couldn't figure it out.

In the code ^ is used to escape <, otherwise it will show this error:

< was unexpected at this time.

Getting the same error using \ to escape

diwatu
  • 5,641
  • 5
  • 38
  • 61
  • 1
    `-replace` is a regex operator and `^` is a regex metacharacter describing the starting position of a string. Since no string starts in multiple places, it doesn't work. If you're expecting to find a literal caret `^` you need to escape it with a backslash, eg. `\^ – Mathias R. Jessen Jan 20 '22 at 19:39
  • without ^ there will be error on <, ^ is used to escape. Tried with your suggestion ,doesn't work either, but thanks a lot. – diwatu Jan 20 '22 at 19:44
  • 1
    `^` is not an escape sequence in neither regex nor PowerShell. Are you running this from a batch script? Or interactively from `cmd.exe`? – Mathias R. Jessen Jan 20 '22 at 19:45
  • I run this from a batch file, also directly from cmd.exe, same result – diwatu Jan 20 '22 at 19:50
  • Please update the question with this detail (it's quite important, "< was unexpected at this time." is from `cmd.exe`, not PowerShell) – Mathias R. Jessen Jan 20 '22 at 19:54
  • 1
    Sorry, @MathiasR.Jessen I have a complex batch file, that is just part of the script, I should have made it with more detail. The question is updated with your suggestion. Thanks – diwatu Jan 20 '22 at 20:00

2 Answers2

3

You need to \-escape all " characters that you want to pass through to the PowerShell command that is ultimately executed, after the PowerShell CLI has stripped unescaped " characters, if any, during command-line parsing:

powershell -Command (gc D:\xxxxxxx\index.html) ^   
 -replace '^<script src=\"js/locale/languageholder.js\"^>^</script^>', '' ^
  | Out-File -encoding ASCII \"D:\yyyyyyyyy\index.html\"

See this answer for more information.

mklement0
  • 382,024
  • 64
  • 607
  • 775
1

The easiest way is to have an external powershell file:

replace.ps1:

(gc index.html) -replace '<script src="js/locale/languageholder.js"></script>' |
  set-content index2.html

Then run:

powershell -file replace.ps1
js2010
  • 23,033
  • 6
  • 64
  • 66