Search code examples
windowsrenamenaming

Is there a way I can bulk remove part of a filename for 900ish files?


Need a way to remove parts of a filename.

Have tried some Basic notepad++ stuff lol

https://i.sstatic.net/7mjqT.jpg

Image shows mainly what I need!

e.g

sevenberry_island_paradise-SB-4131D1-4-S5090015(.jpg) to sevenberry_island_paradise-SB-4131D1-4(.jpg)

The item codes are after the SB-, e.g 4131D1-4, everything after this I don't want.

Any way of removing this from all these files would be a huge huge huge help!!

Thanks!!


Solution

  • The question is not appropriate as posted and you need to post what you have tried and ask for help with your own code and any error messages or unexpected results you encounter. That being said, I see your problem and it seemed like fun to figure out a solution so I have done that.

    This code will find all the files inside the specified directory (you can add the -Recurse parameter to the Get-ChildItem line to get the files in all subdirectories too) and rename them all, removing the end of the file name using RegEx.

    Make a copy of your files before trying this. I have tried my best to create a solution that will work for the file names that you pictured, but if the file names are very different than what is pictured then you may have unintended results. Take a backup first.

    # Specify the path in which all of your jpgs are stored
    $path = 'C:\Path\To\Jpgs'
    # Get all of the files we want to change, and only return files that have the .jpg extension
    $jpgs = Get-ChildItem -Path "$path" <#-Recurse#> | Where-Object {$_.Extension -eq '.jpg'}
    # Perform the same steps below on every file that we got above by using foreach
    foreach ($jpg in $jpgs) {
        # Store the original file name in a variable for working on
        [string]$originalBaseName = "$($jpg.BaseName)"
        # Use RegEx to split the file name
        [string]$substringToReplace = ($originalBaseName -split '-[0-9]+-')[1]
        # Re-add the '-' to the string which you want to remove from the file name
        [string]$substringToReplace = '-' + $substringToReplace
        # Remove the portion of the file name you want gone
        [string]$newBaseName = $originalBaseName -replace "$substringToReplace",''
        # Rename the file with the new file name
        Rename-Item -Path "$($jpg.FullName)" -NewName "$newBaseName$($jpg.Extension)"
    }