Josh James
Josh James

Reputation: 7

Powershell replace a string like "-anything_" with "_"

I am trying to replace a string in my file names. The string always begins with a "-" and ends with a "_". The middle could be numbers, text or both.

I have had success changing "-" to "", but the regex is killing me. I am a complete beginner, so this whole code is cobbled together from other articles.

$baseDirectory = "C:\Test\Rename\"
$a = "\-(.*?)\_"
$b = "_"

$Include = '*.jpg'

Pushd $baseDirectory

Get-ChildItem -Filter "*$a*" -Recurse|
  Rename-Item -NewName {$_.Name -replace $a,$b} -ErrorAction SilentlyContinue

PopD

Goal
A121000-22_01.jpg --> A121000_01.jpg
A478BFE-876_02.jpg --> A478BFE_02.jpg
A124568-59B_03.jpg --> A124568_03.jpg

The result is no change.

Upvotes: 0

Views: 542

Answers (1)

ctwheels
ctwheels

Reputation: 22837

Your existing regex is very close. There's no need to replace with _.

Option 1

You can change the lazy quantifier (.*?) to a character exception class [^_]* as can be seen here.

-[^_]*

This matches:

  • - this character literally.
  • [^_]* any character except _ any number of times (this stops once it reaches _).

Option 2

If you need to ensure the _ character exists, then you can use the following instead as seen here (notice the last line doesn't get matched).

-[^_]*(?=_)

This matches:

  • - this character literally.
  • [^_]* any character except _ any number of times (this stops once it reaches _).
  • (?=_) ensures the following character is _ literally

Additionally

I changed your code to the following and it worked for me (replaced -Filter "*$a*" with -Include "*.jpg"):

$baseDirectory = "C:\test\Rename"
$a = "-[^_]*(?=_)"

Pushd $baseDirectory

Get-ChildItem -Include "*.jpg" -Recurse|
  Rename-Item -NewName {$_.Name -replace $a,""} -ErrorAction SilentlyContinue

PopD

Upvotes: 1

Related Questions