I have a folder with 10 files. I have been able to rename them all using a script I created to add '1 - ' at the beginning of the file names in order. So, each file starts with '1 - ', '2 - ' etc.
Two questions here:
When I re run the script, it does not recognise that the file already has a '1 - ' at the start and so it just adds another 'X - ' at the start of it again. E.g. '1 - 2 - XXXX'
I would like to add to the script to say, where the file already has a prefix of '1 - ' (1 can be any number), then the script should not rename it again (like point 1 above)
Finally, if I add any new files into the same folder, I would like the new files to have the prefix number from the last number in the folder e.g.
Folder contains:
1 - XXXX 2 - XXXX 3 - XXX
If I add a fourth file and run the script the new output should be:
1 - XXXX 2 - XXXX 3 - XXX 4 - XXX
Previous files are not affected and the new file starts at 4.
Any help would be appreciated!
UPDATE: As requested, I have added my current script here: enter image description here
Here is my suggestion:
function renum_files() {
var folder = DriveApp.getFolderById('###'); // paste your folder ID here
var files = folder.getFiles();
var files_to_renum = []; // array of files to renum
var already_numered_files = []; // array of file names that already have number
// fill the two arrays with files or file names
while (files.hasNext()) {
var file = files.next();
if (file.getName().match(/^\d+ -/)) {
already_numered_files.push(file.getName())
} else {
files_to_renum.push(file);
}
}
// do nothing if there are no files
if (files_to_renum.length == 0) return;
// sort the files alphabetically
files_to_renum.sort((a,b) =>
a.getName().toLowerCase() > b.getName().toLowerCase() ? 1 : -1);
// set the counter
var counter = 0;
// UPDATE --------------
if (already_numered_files.length > 0) {
// get all numbers
var counters = already_numered_files.map(x => x.split(' - ')[0]);
// get a bigger number from the numbers
counter = Math.max(...counters);
}
// END UPDATE ----------
// rename the files
files_to_renum.forEach(f => f.setName(++counter + ' - ' + f.getName()));
}