Sachiko
Sachiko

Reputation: 924

How to escape and replace '\' in PowerShell

We'd like to replace \ to \\ in our master files, which can prevent upload on Redshift (once replaced \\ can be uploaded without issue and it would be uploaded single \, same as original customer data).

I tried to replace \ to \\ as follows but received a regular expression error in PowerShell:

Param(
    [string]$TargetFileName
)

# replace words
$old='`\'
$new='`\`\'

# replace \ to \\ for Redshift upload
$file_contents=$(Get-Content "$TargetFileName") -replace $old,$new
$file_contents > $StrExpFile

Error Message:

+ $file_contents=$(Get-Content "$TargetFileName") -replace $old,$new
+                  ~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (`\:String) []、RuntimeException
    + FullyQualifiedErrorId : InvalidRegularExpression

Simply doing -replace '\','\\' didn't work either.

We'd like to save it as the same file name, but the file size can be big, so if you have any better ideas, also would be so much appreciated.

Upvotes: 3

Views: 9538

Answers (2)

yu yang Jian
yu yang Jian

Reputation: 7181

I use a command with parameter , which will replace store:Schema="abcd" to empty string, I escape " to "" or """" as:

powershell -Command "$varStr='store:Schema=""abcd""""'; $filePath='%~dp0SomeFolder\SomeFile.txt'; (gc $filePath) -replace $varStr, '' | Out-File $filePath"

Upvotes: 0

Mark Wragg
Mark Wragg

Reputation: 23405

-Replace uses regular expressions, and in RegEx \ is a special character (the escape character) so to escape a single slash you need to use another slash: \\. Note this is only true for $old (the text you want to match) the replacing text $new is not a regex, so here you still just need \\.

$old = '\\'
$new = '\\'
$file_contents = (Get-Content "$TargetFileName") -replace $old,$new

Alternatively, you could use the .replace() method which doesn't use regular expressions:

$old = '\'
$new = '\\'
$file_contents = (Get-Content "$TargetFileName").replace($old,$new)

Upvotes: 6

Related Questions