0

I have hundreds of Google Docs, and lots of Google Folders. They share a common string in the filename. The Docs need to go into the corresponding Folder, and I'd like to automate this with some Script.

What I want to do is as follows:

I have hundreds of Google Docs which follow a similar pattern in the filename:

SURNAME, Forename_userID_fileName

So for instance,

DOE, Jane_jd5678_Document3
PUBLIC, Tom_tp9123_reportTPS
SMITH, John_js1234_finaldocument

and so on and so forth.

I also have corresponding Folders in a Google Team Drive, set up as follows:

SURNAME, Forename (userCode) (userID) - userType

So for instance,

DOE, Jane (145374578) (jd5678) - AET Full Time
PUBLIC, Tom (673468714) (tp9123) - NR Full Time
SMITH, John (874512456) (js1234) - AET Part Time

The common string between the files and the folder names is the userID string.

Currently I download all the Docs, and then upload drag-and-drop into each corresponding folder. Takes ages! I was hoping there is a bit of Apps Script that I can do to automate this but I really don't know where to start at all. Anyone have any pointers?

This StackOverflow question seems to want to do what I want to do, but as I'm such a beginner with Apps Script I can't really decipher the solution.

tehhowch
  • 9,645
  • 4
  • 24
  • 42
  • Possible duplicate of [Google Team Drive Move file between team drive folders using Apps Script](https://stackoverflow.com/questions/49670353/google-team-drive-move-file-between-team-drive-folders-using-apps-script) – tehhowch Apr 26 '19 at 11:41

1 Answers1

0

This is a basic example to point you in the right direction using the basic Google Apps Script DriveApp (as opposed to the advanced Script Services version or other Google Drive API methods). The main concern that comes to mind is the script timing out if this example takes too long to complete. If that happens, you'll need a more complex solution. You could also chunk it up by having the idRegex only work on, e.g., surnames A-D then E-G, etc. The example regular expression could match random files you have with underscores; you may want to find a more complicated regular expression if that is a concern.

function organizeFilesById() {
  var idRegex = /_[A-z]+[0-9]+_/;
  var files = DriveApp.getFiles();
  while (files.hasNext()) {
    var file = files.next();
    var filename = file.getName();
    var id = idRegex.exec(filename);
    if (! id) {
      continue;
    } else {
      id = id[0];
    }
    var query = "title contains '" + id + "'";
    var folders = DriveApp.searchFolders(query);
    if (folders.hasNext()) {
      var folder = folders.next();
      Logger.log("Will add %s to %s", filename, folder.getName());
      //folder.addFile(file); // uncomment line to actually do it
    } else {
      Logger.log("No folder found for %s", filename);
      // could create folder or just report "folder not found"
    }
  }
}
dwmorrin
  • 2,704
  • 8
  • 17