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.
-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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With