Malmier
Malmier

Reputation: 31

Replace character from link with powershell

I would like replace ? in

"EquipmentInfo["?"] = "<iframe src='http://bing.fr'></iframe>";"

by a variable.

I tried this:

(get-content C:\word.txt) -replace '?', '$obj' | Set-Content C:\word.txt

Upvotes: 2

Views: 64

Answers (2)

mklement0
mklement0

Reputation: 439307

This answer explains the original problem.
jisaak's helpful answer provides a comprehensive solution.

The -replace operator takes a regular expression as the first operand on the RHS, in which ? is a so-called metacharacter with special meaning.

Thus, to use a literal ?, you must escape it, using \:

(get-content C:\word.txt) -replace '\?', $obj   

Note: Do not use '...' around $obj, unless you want literal string $obj; generally, to reference variables inside strings you must use "...", but that's not necessary here.

A simple example with a literal:

'Right?' -replace '\?', '!' # -> 'Right!'

Upvotes: 2

Martin Brandl
Martin Brandl

Reputation: 58991

I would use a positive lookbehind to ensure you find the right question mark. Also you have to use double quote on your replacement since you want to replace a variable:

(get-content C:\word.txt -raw) -replace '(?<=EquipmentInfo\[")\?', "$obj" | Set-Content C:\word.txt

Regex used:

(?<=EquipmentInfo\[")\?

Regular expression visualization

Upvotes: 3

Related Questions