2

I am trying to use PowerShell do a simple find and replace. Essentially, I used to have some support files in a directory with the same name of a "master" file. All but one of those support files are no longer necessary. The "master" file has a text reference to the path of the other file. What I want to do is modify this path in the "master" file to remove the deleted directory.

For example, let's say I have the file C:\Temp\this+that.txt I used to have C:\Temp\this+that\this+that.dat that has now been moved to C:\Temp\this+that.dat

C:\Temp\this+that.txt has a line like this:

/temp/this+that/this+that.dat

I would like this line to become:

/temp/this+that.dat

I have lots of these files that a batch file is moving. Everything is working fine using the powershell command below for all file names that do NOT contain a plus + sign. For those files, the call below does not work.

powershell -Command "(gc '!CURRENT_FILE!') -replace '/!BASE_NAME!/', '/' | Set-Content '!CURRENT_FILE!'"

For the example above, CURRENT_FILE would be C:\Temp\this+that.txt and BASE_NAME would be this+that

Can anyone help me with why this isn't working for file names that contain a plus + sign?

BenH
  • 9,766
  • 1
  • 22
  • 35
NickB
  • 21
  • 2
  • 2
    The problem here is that you're treating `!BASE_NAME!` as a regular expression. I don't know my way around PowerShell, but [this answer looks like it might help](https://stackoverflow.com/questions/23651862/powershell-how-to-escape-all-regex-characters-from-a-string#23651909). Basically you'll need to escape all characters with special Regex-meaning before interpolating it into the expression. – Marcus Ilgner May 24 '17 at 18:34
  • 2
    @ma_il is exactly right. The '+' character is a special character in RegEx, so you will need to escape it. `"(gc '!CURRENT_FILE!') -replace [regex]::escape('/!BASE_NAME!/'), '/' | Set-Content '!CURRENT_FILE!'"` – TheMadTechnician May 24 '17 at 18:38

1 Answers1

2

@ma_il is exactly right. The '+' character is a special character in RegEx, so you will need to escape it.

powershell -Command "(gc '!CURRENT_FILE!') -replace [regex]::escape('/!BASE_NAME!/'), '/' | Set-Content '!CURRENT_FILE!'"
TheMadTechnician
  • 34,906
  • 3
  • 42
  • 56