1
votes

Could you post a Snippet that does find & replace across all files within a folder please?

I did find something similar, Google Scripts - Find and Replace Function that searches multiple documents

but that one search in every file in Google Drive, not within a folder. Since I'm only learning Google Apps Script by example now, I can't make that tiny step myself.

EDIT: Further on the replacing part.

The DocumentApp.openById returns a type of Document right?

However, I can't find the replaceText method in the Document type doc: https://developers.google.com/apps-script/reference/document/document

Fine, I then dig deeper, and found another example, Google Apps Script document not accessible by replaceText(), which indicates that the replaceText method should be invoked from var body = doc.getActiveSection(). However, I can't find the getActiveSection method in the Document type doc either.

Please help. thx

1
var doc = DocumentApp.openById('doc id'); var body = doc.getBody(); body.findText('searchPattern') instead of body you can work with headers and footers...Serge insas

1 Answers

2
votes

The first thing is to get a hold of your folder, this can be done in a few ways.

If you are writing a script for a limited audience, and you are working with only a particular folder you can use DriveApp.getFolderById(id). The id can be found in the url of your drive web app when you navigate to a folder as such:

https://drive.google.com/a/yourcompany.com/?tab=mo#folders/0B5eEwPQVn6GOaUt6Vm1GVjZmSTQ

Once you have that id, you can simply using the same code in the answer you reference, iterate through the file iterator for that particular folder as such:

function myFunction() {
  var files = DriveApp.getFolderById("0B5eEwPQVn6GOaUt6Vm1GVjZmSTQ").getFiles();
  while (files.hasNext()) {
    var file = files.next();
    Logger.log(file.getName());
    var doc = DocumentApp.openById(file.getId());
   doc.replaceText("My search string or regex", "My replacement string");
 }
 Logger.log("Done")
}

Alternative way of getting the folder if you only know its name are the use of DriveApp.getFoldersByName(name) which returns a folder iterator. If you know you have only one folder of that name, then you need to simply get the first and only element in the iterator as such:

function myFunction() {
  var folders = DriveApp.getFoldersByName("myfoldername");
  var myFolder = null;
  if (folders.hasNext())
    myFolder = folders.next();
  if (myFolder !== null) {
    // do stuff
  } else {
    // exit gracefully
  }

Further if you have multiple folders with the same name, you would have to iterate through them in a while loop (similar to the file iterator in the code you linked) and find a marker that proves this is the folder you are looking for (i.e. you could have an empty file with a particular name in there)