Hi I want to count the number of files having a specific string in their filename in a specific folder in Drive. For example I want to count all files that have the string "final" in their name in a specific folder. I am able to get it to work by giving the search string within quotes, but not if i pass it as a variable.
See lines commented as // doesn't work and // works below. Appreciate any help
function countNumFiles(){
var searchString = "some string";
const folderID = 'Replace_with_folder_id';
var searchFor = 'title contains ' searchString ; // doesn't work
//var searchFor = 'title contains "some string"'; // works
var filesArray = [];
var folder = DriveApp.getFolderById(folderID).searchFiles(searchFor);
while (folder.hasNext()) {
var file = folder.next();
filesArray.push(file.getName());
}
Logger.log(filesArray.length);
}
CodePudding user response:
In your script, how about the following modification?
From:
var searchFor = 'title contains ' searchString ;
To:
var searchFor = `title contains '${searchString}'`;
or
var searchFor = "title contains '" searchString "'";
CodePudding user response:
Find Search String in File Name for files in a given folder
function countFilesWithStringsInNames() {
const s = "searchstring";//enter search string
const folder = DriveApp.getFolderById('folderid');
const files = folder.getFiles();
let found = [];
while(files.hasNext()) {
let file = files.next();
if(~file.getName().indexOf(s)) {
found.push(file.getId())
}
}
Logger.log(found.length);
}
or with Drive API Version 2:
function countFiles() {
const s = "title search string";
const folderid = "folderid";
const files = Drive.Files.list({supportsAllDrives : true,q:`title contains '${s}' and parents in '${folderid}'`}).items;
let o = files.map(items => [items.id]);
Logger.log(o.length);//o contain a column of ids for each file found
}