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?

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. Basically you'll need to escape all characters with special Regex-meaning before interpolating it into the expression. Commented May 24, 2017 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!'" Commented May 24, 2017 at 18:38

1 Answer 1

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!'"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.