0

I have a bunch of Google Docs that I want to concatenate into a fresh new doc. Basically I want to do the equivalent of the Unix command:

cat 1.txt 2.txt 3.txt >4.txt

I can't seem to figure out the best way to do this from the Apps Scripts documentation. Would anyone happen to know?

I tried the following:

// ... code omitted
var entries = [];
while (files.hasNext()) {
    var file = files.next();
    var name = file.getName();
    if (file.getOwner().getName() != 'My Name') continue

    var re = /Pattern I am looking for - \d\d/g;
    if (name.match(re) == null) continue;

    entries.push( {"Name" : name, "File" : file} );
}
entries.sort(function(a,b) { return a.Name.localeCompare(b.Name); });

// Open the Full.txt file and add each file into it in sequence.
var fullDoc = DocumentApp.create('Full.txt');
entries.forEach(function(e) {
    var contents = e.File.getAs('text/plain');
    // Haven't yet gotten to sticking contents into the target file
    // because content retrieval itself fails with the message:
    //  "Converting from application/vnd.google-apps.document to text/plain 
    //  is not supported. (line 51, file "DocMerge")"
    return;
  });

Thanks.

-av

  • Add more detail about your search/research efforts. Reference [ask]. – Rubén Oct 17 '17 at 01:00
  • I'd try [DocumentApp's](https://developers.google.com/apps-script/reference/document/document-app) [Body Class](https://developers.google.com/apps-script/reference/document/body) and maybe the [getText()](https://developers.google.com/apps-script/reference/document/body#getText()) with [DriveApp's](https://developers.google.com/apps-script/reference/drive/drive-app) file [setContent()](https://developers.google.com/apps-script/reference/drive/file#setContent(String)) – random-parts Oct 17 '17 at 01:28
  • There doesn't seem to be a way to get the Body from a File. What I have is a list of File objects. – Anand Venkataraman Oct 18 '17 at 16:17
  • @Rubén - docContent = thisFile.getAs('text/plain'); referenced in the answer you cite doesn't work because it says getAs('text/plain') is not supported. See the inline comment in my posted code? – Anand Venkataraman Oct 18 '17 at 16:19
  • The "problem" is that code on this question is using DocumentApp instead of DriveApp. – Rubén Oct 18 '17 at 23:38

1 Answers1

0

You need to open the Files using DocumentApp, so you can retrieve the document contents. As you are seeing, straight conversion to plaintext is not supported (although it would be convenient).

var source_doc = DocumentApp.openById(e.File.getId());
var contents = source_doc.getBody().getText();

Depending on your use case, you may also want to get the header/footer sections, and you could also skip using getText() and use Body.copy() to create a copy of the body element you can then insert into the other doc. This approach would preserve formatting.

Cameron Roberts
  • 7,127
  • 1
  • 20
  • 32