Search code examples
windowspowershellbatch-rename

Files bulk renaming - match a predefined text file


Good day,

I am trying to rename/organize files based on the match/lookup found in the text file.

I have a couple of hundred Cyrillic(Russian) named media files in a folder like this:

  • файл 35.avi
  • файл34.avi
  • файл2 4.avi
  • файл14.avi

*note that some files have spaces

The text file, with the desired names, looks like this:

  • файл 35.avi| 4. файл 35.avi
  • файл34.avi| 3. файл34.avi
  • файл2 4.avi| 1. файл2 4.avi
  • файл14.avi| 2. файл14.avi

The reason it looks that way (with | as a separator) is because I tried using "Bulk Renaming Utility" which uses pipe | as a separator for "Rename Pairs" function. So essentially, the filename to the right of pipe | is the final product. Unfortunately, that function does not work with Cyrillic(Russian) or other non standard characters.

I found PowerShell script HERE which appears to be almost what I need except that it does not match file names before renaming. Similarly, I found this Python script HERE which does what i need but it's for Ubuntu. Unfortunately, I am on a Windows7 and not sure it applies to me.

Any recommendations?

Thank you very much for your time!


Solution

  • You could read the text file into a hashtable, where the key is the old name (the value on the left hand side of the |), and the value is the new name:

    $RenameTable = @{}
    Get-Content textfile.txt |ForEach-Object {
        $OldName,$NewName = $_.Split('|')
        $RenameTable[$OldName] = $NewName
    }
    

    Then rename the files based on what is in the hashtable:

    Get-ChildItem .\folder\with\avi\files |Rename-Item -NewName {
        if($RenameTable.ContainsKey($_.Name)){ 
            $RenameTable[$_.Name] 
        } else { 
            $_.Name 
        }
    }