Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the replace operator on a string that has quotes powershell

I am looking to run the command

foreach-object {$_ -replace

However the string I am attempting to work with could be described as the follow

this string "has" quotes

the whole line being

foreach-object {$_ -replace "this string "has" quotes", "this string "won't have" quotes"}

How do I make this quote filled line work with powershell?

like image 436
mhopkins321 Avatar asked Jun 25 '12 15:06

mhopkins321


People also ask

How do you replace part of a string in PowerShell?

You can call the PowerShell replace method on any string to replace any literal string with another. If the string-to-be-replaced isn't found, the replace() method returns nothing. You don't need to assign a string to a variable to replace text in a string.

How do you escape a quote from a string in PowerShell?

To prevent the substitution of a variable value in a double-quoted string, use the backtick character ( ` ), which is the PowerShell escape character. $i = 5 "The value of `$i is $i."

How do I replace a single quote in PowerShell?

Use the PowerShell String replace() method or replace operator to replace the single quote in PowerShell with empty space or double quotes. e.g. $str. replace("'",'') replace the single quotes with an empty string. The replace() method returns a string where all single quote is replaced.

How do you replace double quotes in PowerShell?

Using the PowerShell replace() method, it can replace all double quotes in a string with single quotes. $str = 'This is an "embedded quote" in a string. '


1 Answers

You can either escape the nested double quotes like so `" or better yet, use single quotes for quoting of the string then you won't need to escape the double quotes e.g.:

'this string "has" quotes'

Note: with single quotes you won't get variable expansion in a string.

like image 67
Keith Hill Avatar answered Oct 03 '22 06:10

Keith Hill