Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I replace a string with a dollar sign in it in powershell

Tags:

powershell

In Powershell given the following string

$string = "this is a sample of 'my' text $PSP.what do you think"

how do I use the -replace function to convert the string to

this is a sample of 'my' text Hello.what do you think

I obviously need to escape the string somehow, Also $PSP is not a declared variable in my script

I need to change all mentions of $PSP for some other string

like image 481
Kev Hunter Avatar asked Feb 02 '12 11:02

Kev Hunter


People also ask

How do I replace a character in a string in PowerShell?

You don't need to assign a string to a variable to replace text in a string. Instead, you can invoke the replace() method directly on the string like: 'hello world'. replace('hello','hi') . The tutorial is using a variable for convenience.

How do I use the dollar sign in PowerShell?

Working with variables The default value of all variables is $null . To get a list of all the variables in your PowerShell session, type Get-Variable . The variable names are displayed without the preceding dollar ( $ ) sign that is used to reference variables.

How do I change special characters in PowerShell?

Replacing characters or words in a string with PowerShell is easily done using either the replace method or -replace operator. When working with special characters, like [ ], \ or $ symbols, it's often easier to use the replace() method than the operator variant.

How do I replace a string in a PowerShell file?

Use Get-Content and Set-Content to Replace Every Occurrence of a String in a File With PowerShell. The Get-Content gets the item's content in the specified path, such as the text in a file. The Set-Content is a string-processing cmdlet that allows you to write new content or replace the existing content in a file.


1 Answers

Use the backtick character (above the tab key):

$string = "this is a sample of 'my' text `$PSP.what do you think"

To replace the dollar sign using the -replace operator, escape it with backslash:

"this is a sample of 'my' text `$PSP.what do you think" -replace '\$PSP', 'hello'

Or use the string.replace method:

$string = "this is a sample of 'my' text `$PSP.what do you think"
$string.Replace('$PSP','Hello)'

this is a sample of 'my' text Hello.what do you think

like image 118
Shay Levy Avatar answered Oct 06 '22 09:10

Shay Levy