How to loop through sub folders and rename to parent – folder – file number

batch-rename

Here are my folders:

Dexter\Season 1\season 1 ep 1  
Dexter\Season 1\season 1 ep 1  
Dexter\Season 2\season 1 ep 1  
Dexter\Season 2\season 1 ep 1  
Dexter\Season 3\season 1 ep 1  
Dexter\Season 3\season 1 ep 1  

I am currently in Dexter\

What I want to do is loop through all the sub folders in Dexter and rename all the files accordingly:

Dexter\Season 1\season 1 ep 1 -> Dexter\Season 1\1x1

How would I go about doing this?

Best Answer

Since I'm wasting my summer inside anyways I might aswell do something helpful, and write the script for you. Assuming you're using Windows, the following PowerShell script would fit your scenario (just save as a .ps1 file and modify the path at the top).

$TVShowFolderPath = "X:\Series\Dexter";

$TVShowSeasons=$(get-childitem "$TVShowFolderPath");

foreach( $s in $TVShowSeasons)
{
    if( ($s.PSisContainer) -and ($s -imatch "^(Season )(\d{2}|\d{1})$") )
    {
        $season = $matches[2];
        write-host "Season $season";

        $episodes=$(get-childitem $s.FullName);

        foreach( $ep in $episodes)
        {
            if( $ep -imatch "^(season) (\d{2}|\d{1}) (ep) (\d{2}|\d{1})(.*)$")
            {
                $newName = "$($season)x$($matches[4])$($matches[5])";
                write-host "`tEpisode: `"$($ep.Name)`" --> `"$newName`"";
                Rename-Item $ep.FullName $newName;
            }
        }
    }
}

If you want to see if it spits out the correct names first just comment out the line starting with "Rename-Item".

Related Question