Basically, I have a bunch of files in a shared google drive, let's say:
AA123_1.jpg
AA123_2.jpg
AA123_3.jpg
…
I am trying to get rid of all of the "123"'s and replace them with an empty space, or just replace "123_" with "_". I am not particularly familiar with google scripts (I do understand basic programming logic though), but yeah, basically I was wondering if anyone knows how I could make a script for this as there is a very large amount of files. Thanks ever so much.
Best Answer
In a given folder of Google Drive, you have a number of jpg images, each with a consistent file name structure ("AA123_y.jpg, where y is a single or multi-digit sequence number).
You want to rename these files to remove the third, fourth and fifth digits ("123").
For example, "AA123_1.jpg" -> "AA_1.jpg"; "AA123_1003.jpg" -> "AA_1003.jpg".
Logic
getFolderById()
is used to identify the specific folder on Google Drivevar mimetype = 'image/jpeg';
- this is a user defined variable; in this case the mime type is used to limit the files whose names will be changed to only jpg files.getMimeType();
returns the mime type of a specific file.ftype.indexOf(mimetype );
- a test to see if the file is the given mime type.indexOf
returns "-1" if the index is not found, hence the IF statement.var fname = myname.replace("123_", "_");
- uses the Javascript "replace" method to remove the third, fourth and fifth character and sixth characters which is ="123_". The script replaces the underscore because there is possibility of a file named "AA123_123.jpg", in which case the second "123" is not to be replaced.myfile.setName(fname);
- updates the file nameSample - Before
Sample - After
Note: the jpg files have been renamed, but the spreadsheet (which has a similar naming pattern) has not been renamed.