Search code examples
windowsbatch-rename

How to rename a few thousand files by removing everything including and after the last occurance of "by" in the filename


I have a few thousand files where the author name is contained in the filename of the file. The main problem this creates is that the filename becomes too long as all authors are mentioned and moving them to different folders becomes impossible to due windows filename length limit. I need to rename the files by removing everything after the last occurance of "by " including the "by " itself.

The only way to rename so many files is to write a program of some sort. What would be the quickest way to do this?


Solution

  • You can use a PowerShell script to rename multiple files. Give this a try:

    $cur_dir = pwd
    $files = Get-ChildItem $cur_dir
    foreach($file in $files){
        $rev_name = $file.name
        $rev_name = $rev_name.ToCharArray()
        [Array]::Reverse($rev_name)
        $rev_name = -join $rev_name
        $indi = $rev_name.IndexOf("yb")
        if($indi -ge 0){
            $start_ind = $rev_name.length - $indi-2
            $final_name = $file.name.substring(0,$start_ind)
            Rename-Item -Path $file.name -NewName $final_name
          }
      }
    

    I hope it helps.