Apps Script to organize Drive files into folders based on filename patterns

I’m trying to sort files in my Google Drive. All the files are in one folder now. They have names like ‘123456789_something.psd’ or ‘123456789_anotherthing.jpg’. I want to group these files into folders named after the first part of their filenames.

For instance, if I have these files:

555666777_main.psd
555666777_extra.jpg
555666777_more.jpg
888999000_main.psd
888999000_extra.jpg

I’d like a script that creates folders ‘555666777’ and ‘888999000’, then moves the matching files into them.

Can someone help me write an Apps Script to do this? It needs to work for both PSD and JPG files. Thanks!

I’ve actually tackled a similar file organization challenge before. Here’s a script that should do the trick for you:

function organizeFiles() {
  var folder = DriveApp.getFolderById('YOUR_FOLDER_ID_HERE');
  var files = folder.getFiles();
  
  while (files.hasNext()) {
    var file = files.next();
    var fileName = file.getName();
    var match = fileName.match(/^(\d+)_/);
    
    if (match) {
      var folderName = match[1];
      var subFolder = folder.getFoldersByName(folderName);
      
      if (subFolder.hasNext()) {
        subFolder.next().addFile(file);
      } else {
        var newFolder = folder.createFolder(folderName);
        newFolder.addFile(file);
      }
      
      folder.removeFile(file);
    }
  }
}

Just replace ‘YOUR_FOLDER_ID_HERE’ with the ID of your main folder. This script will work for any file type, not just PSDs and JPGs. It creates folders based on the number prefix and moves files accordingly. Remember to grant necessary permissions when running the script for the first time. Hope this helps!

hey dave, i’ve done something similar before. here’s a quick tip: instead of moving files, try using shortcuts. create folders based on those number prefixes, then make shortcuts to the original files in those folders. this way, you keep your originals in one place but still get that organized folder structure. saves time on moving stuff around too. lemme know if you need more help!

Having dealt with similar file organization tasks, I can offer some insights. While the provided script is a good starting point, you might want to consider a few optimizations. First, batch your folder creations and file moves to reduce API calls and improve performance. Second, implement error handling to manage potential issues like duplicate file names or insufficient permissions. Lastly, consider adding a logging mechanism to track the script’s progress, especially useful for large file sets. These enhancements can significantly improve the script’s efficiency and reliability. If you need help implementing these improvements or run into any issues, feel free to ask for more specific guidance.