在Google脚本中替换文件名中的文本

时间:2016-07-27 10:54:23

标签: google-apps-script google-sheets

我想复制一个文件并同时重命名。我的脚本在目录中搜索所有相关文件,副本然后重命名它们。我可以将它们复制到一个不同的目录中,或者在名称后附加一些内容,但是我找不到如何用其他文本替换名称中的部分文本。

我尝试过replace和replaceText,似乎都没有更改文件名,而是查看文件的内容。在下面的代码中,我想将文件名保存到FileRenameStart中,然后将Oldmonth替换为NewMonth,但我找不到正确的方法来执行它。有人能帮忙吗?

由于

    function newMonthFunction() {

  // what files we want
 var OldMonth = "July 2016";
 var NewMonth = "August 2016";
 var FindThisText = "Core " + OldMonth;
 files = DriveApp.searchFiles('title contains "' + FindThisText + '"  and mimeType = "application/vnd.google-apps.spreadsheet"');
 var files = DriveApp.searchFiles('title contains "' + FindThisText + '" and mimeType = "application/vnd.google-apps.spreadsheet"');

  while (files.hasNext()) {
    var file = files.next();
    Logger.log(file);
    var file = DriveApp.getFileById(file.getId());
    var FileRenameStart =file.getName();
    var FileRenameend =FileRenameStart
    DriveApp.getFileById(file.getId()).makeCopy(FileRenameEnd)

    }
}

1 个答案:

答案 0 :(得分:0)

您已接近解决此问题。它应该适合你:

function newMonthFunction() {
  var OldMonth = "July 2016";
  var NewMonth = "August 2016";
  var FindThisText = "Core " + OldMonth;
  var files = DriveApp.searchFiles('title contains "' + FindThisText + '" and mimeType = "application/vnd.google-apps.spreadsheet"');

  while( files.hasNext()){
    //getting the old file
    var file = DriveApp.getFileById(files.next().getId());
    //getting the old filename and replacing the old month by the new one
    var newName = file.getName().replace(OldMonth,NewMonth);
    //copying the old file using a new name for copy
    var newFile = file.makeCopy(newName);
    //logging the new filename
    Logger.log(newFile);
  }
}