How would I batch rename file in a directory from [string x]_[string y].properties to [string y]_[string x].properties?

48 views Asked by At

I was manually renaming about 450 files for a project I'm working on and realized 400 in that it would be easier if "y" came first in the order, but I was too far in by that point to change it. Is there I way I could automatically do that?

Example:

-cloth_ball.properties
-cloth_puppet.properties
-plastic_ball.properties
-plastic_puppet.properties
-wooden_ball.properties
-wooden_puppet.properties

Needs to be:

-ball_cloth.properties
-ball_plastic.properties
-ball_wooden.properties
-puppet_cloth.properties
-puppet_plastic.properties
-puppet_wooden.properties

I looked for other batch renaming options for help, but I couldn't find any that would help with this specific issue.

2

There are 2 answers

2
Santiago Squarzon On BEST ANSWER

Assuming you have an array of strings:

$strings = @(
    '-cloth_ball.properties'
    '-cloth_puppet.properties'
    '-plastic_ball.properties'
    '-plastic_puppet.properties'
    '-wooden_ball.properties'
    '-wooden_puppet.properties'
)

You can first use the regex pattern (?<=-)([^_]+)_([^.]+) with -replace operator, and then Sort-Object for sorting them:

$strings -replace '(?<=-)([^_]+)_([^.]+)', '$2_$1' | Sort-Object

See https://regex101.com/r/e7kggt/2 for regex details.

0
JRev On

Building off the previous answer as well as the answer here (Use Regex / Powershell to rename files), you can do this by piping Get-ChildItem for your folder "MyFolder" into Rename-Item.

Get-ChildItem MyFolder | Rename-Item -NewName { $_.Name -replace '([^_]+)_([^\.]+)\.(.+)', '$2_$1.$3'}

As mentioned, regex101 will explain this. See here for this example: https://regex101.com/r/UulvlB/1