Search code examples
windowspowershellbatch-rename

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


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.


Solution

  • 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.