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

6
  • 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. \^<script src=... Commented Jan 20, 2022 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. Commented Jan 20, 2022 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? Commented Jan 20, 2022 at 19:45
  • I run this from a batch file, also directly from cmd.exe, same result Commented Jan 20, 2022 at 19:50
  • 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 Commented Jan 20, 2022 at 20:00

2 Answers 2

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.

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

2 Comments

correct, escaping " is the tricky part. I tried, it works. Thank you mklement0!
Glad to hear it, @Gisway.; my pleasure
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

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.