Prefix the file names in a folder with sequential numbers based on the highest number already used as a prefix

I've successfully used a script to rename the 10 files in a folder by adding '1 - ' to the beginning of each file name. However, I have encountered two issues:

  1. When I run the script again, it mistakenly adds another 'X - ' at the start, resulting in names like '1 - 2 - XXXX'

  2. I want to modify the script so that if a file already has a prefix like '1 - ', it won't be renamed again.

  3. Additionally, when new files are added to the folder, I want them to continue the numbering from the last file. For example:

Folder currently contains:

1 - XXXX 2 - XXXX 3 - XXX

If I add a fourth file and run the script, the output should be:

1 - XXXX 2 - XXXX 3 - XXX 4 - XXX

Existing files remain unchanged while the new file starts at 4.

Any assistance would be greatly appreciated!

UPDATE: I have also included the link to my current script as requested: enter image description here

Answer №1

Check out the following solution:

function renumerate_files() {
  var folder = DriveApp.getFolderById('###'); // input your folder ID here
  var files_in_folder = folder.getFiles();
  var files_to_renumerate = [];          // store files to be renumerated
  var already_numbered_files = [];   // maintain a list of file names with existing numbers

  // populate the two arrays with relevant files or file names
  while (files_in_folder.hasNext()) {
    var current_file = files_in_folder.next();
    if (current_file.getName().match(/^\d+ -/)) {
      already_numbered_files.push(current_file.getName())
    } else {
      files_to_renumerate.push(current_file);
    }
  }

  // exit function if there are no files to renumerate
  if (files_to_renumerate.length == 0) return;
  
  // organize the files alphabetically
  files_to_renumerate.sort((a,b) => 
    a.getName().toLowerCase() > b.getName().toLowerCase() ? 1 : -1);
  
  // initialize the counter
  var counter = 0;

  // UPDATE --------------

  if (already_numbered_files.length > 0) {

    // extract all existing numbers
    var counters = already_numbered_files.map(x => x.split(' - ')[0]);

    // determine the highest number from the extracted numbers
    counter = Math.max(...counters);
  }
  
  // END UPDATE ----------

  // rename the files
  files_to_renumerate.forEach(file => file.setName(++counter + ' - ' + file.getName()));
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Loading drop-down menu content after making an AJAX request

I understand that AJAX functions asynchronously (hence the "A" in AJAX). I have placed all the code that relies on the result of the AJAX call inside the success callback function. However, even after making the call, the select dropdown box is not being p ...

Issue with retrieving data from MySQL database using PHP in Chart.js

I am currently facing an issue while trying to populate a chart using the ChartJS plugin with data from my MySQL database. I keep encountering the error message: mysqli_fetch_assoc(): Couldn't fetch mysqli_result in ... Despite using json_encode, ...

Updating the Structure of Various Objects with an Object Model Schema

Hello there, Query: Can you provide guidance on constructing a function that does the following: Accepts an object as the first argument; Takes a schema model as the second argument; The second argument is an array of objects with different models than t ...

Why is a <script> tag placed within a <noscript> tag?

Lately, I've been exploring various websites with unique designs and content by inspecting their source code. One site that caught my attention was Squarespace, which had blocks of <script> tags within a <noscript> tag: <!-- Page is at ...

Identifying whether a child component is enclosed within a specific parent using React

Is there a more elegant and efficient method to determine if the parent of SeminarCard is Slider? Currently, I am passing this information through a prop. The prop value (true/false) is used to provide additional padding. When used independently: <Semi ...

Connecting a specific URL of an API to a single mobile app: A step-by-step guide

Currently, my API includes a user registration system that is utilized by a mobile application. Most of the URLs are restricted for anonymous users and require a token key for authorization, except for the register URL. The register URL needs to remain op ...

Incorporating an element into a nested array

I have an array stored in a variable called 'items' with various products and their attributes. I am looking to randomly generate a popularity score between 1 and 100 for the items that currently do not have one. This is my current array: const ...

Deceptive scope dilemma?

Seems simple enough, but there's a glitch in the system. $(function(){ (function(){ /** * @return boolean Based on success */ function saveDataOnServer(data){ var success = false; $.ajax({ url : ...

Invoke data-id when the ajax call is successful

Initially, there was a smoothly working "like button" with the following appearance: <a href="javascript:void();" class="like" id="<?php echo $row['id']; ?>">Like <span><?php echo likes($row['id']); ?></span ...

What is the fastest way to efficiently refresh a substantial BufferGeometry?

When using a BufferGeometry to render thousands of cubes forming terrain, I encountered difficulty in updating the geometry when changing the position of a single cube. For instance, this is the code used to initialize the geometry: (My tests are based on ...

Adjust the size of the Div and its content to fit the dimensions of

Currently, I have a div containing elements that are aligned perfectly. However, I need to scale this div to fit the viewport size. Using CSS scale is not an option as it does not support pixel values. https://i.stack.imgur.com/uThqx.png I am looking to ...

The zip() operator in RxJS is not functioning as intended. It consistently finishes execution without emitting any values

Suppose you have an observable containing a large number of elements, say 450 or more. You want to transfer these elements to a different observable in batches of 100 elements each. You can check out a functional example provided by @martin at this link: ...

Customize your Shopify Messenger icon using JavaScript!

Shopify recently introduced a new feature that allows customers to contact store owners through messenger. My client has requested me to customize the appearance of this icon with their branded icon instead. https://i.stack.imgur.com/uytpd.png I have not ...

A guide on effectively utilizing nested arrays within a pcolumn prime ng data table

I have a nested array structure and I am utilizing PrimeNG data table to display the data. Below is the organization of my array: this.institutionalTimetable = [ {day: "Monday", entries: [{startTime: "132", endTime: "789", recess: true, subject: 'Eng ...

Are you patiently anticipating the definition of variables?

As a newcomer to JavaScript, I am experimenting with creating an API that can send requests to other websites and then display the data in an EJS template. I have written some functions to handle the requests, but I am encountering issues when trying to a ...

Server Crash Causes Hapi to Fail Under Request Load

Attempting to create a backend using Hapi for the first time, but encountering issues where the server crashes every time a request is sent. Occasionally, a response is received, but the server eventually crashes on its own. The error message states: Type ...

An error was encountered with Ajax and JSONP due to an unexpected token causing a SyntaxError

Currently attempting to retrieve information from the host at 000webhost The data is in JSONP format: { "categories": { "category": [ { "name": "Android", "parent": "Computer Science", "ID": "2323" }, { ...

Using ng-repeat on a select element is replacing the original content

I'm struggling with the following code snippet: <select> <div class="arrow-up"></div> <option data-ng-repeat="x in y">{{x}}</option> </select> the resulting output doesn't show the arrow div like this ...

Step-by-step guide on making a post request to the Facebook Graph Api with Httparty in a Rails application

I'm currently working on developing a bot for Facebook Messenger, and I need to make a post request call to the Facebook Graph API. The sample code provided by Facebook is in Node.js, but I am working with Rails as my backend framework. Sample Code ...

What methods can be used to reveal the true value of data that has been encrypted?

Is it possible to retrieve the original value of data that has been hashed? Can the hashcode be reversed to reveal the real value of the data? String ida = new String(txtID.getText().toString()); int idb = ida.hashCode(); codeD.setText("result: " + ida) ...