Skip to content

Instantly share code, notes, and snippets.

@dtinth
Last active September 29, 2024 23:08
Show Gist options
  • Save dtinth/93e230152a771dcb1ec5 to your computer and use it in GitHub Desktop.
Save dtinth/93e230152a771dcb1ec5 to your computer and use it in GitHub Desktop.
Batch File Rename Script

Batch File Rename

Use JavaScript for Automation to rename files in batch!

Motivation

While working on some client-side code at Oozou, I often have to rename a lot of image files. For example, Bourbon uses _2x.png for retina images, rather than @2x.png used by Retina.js.

I used to do this manually, until I am fed up and write this script.

Screenshot

var app = Application.currentApplication()
app.includeStandardAdditions = true
var Finder = Application('Finder')
var selection = [].slice.call(Finder.selection())
var code = prompt('How to modify the name?', 'return name')
var fn = new Function('name', code)
try {
var tasks = selection.map(function(item) {
var name = item.name()
try {
var target = fn(name)
} catch (e) {
throw new Error('Cannot rename "' + name + '": ' + e)
}
if (!target) {
throw new Error('Cannot rename "' + name + '": expression returned empty result')
}
return { item: item, from: name, to: target }
}).filter(function(task) { return task.from != task.to })
if (tasks.length == 0) throw new Error('No files to rename!')
var message = 'These files will be renamed:\n\n' +
tasks.map(function(task) { return '- ' + task.from + ' => ' + task.to }).join('\n')
if (confirm(message)) {
tasks.forEach(executeTask)
}
} catch (e) {
alert('Error!', String(e))
}
// Recipes from: https://github.com/dtinth/JXA-Cookbook/wiki/User-Interactions
function prompt(text, defaultAnswer) {
var options = { defaultAnswer: defaultAnswer || '' }
try {
return app.displayDialog(text, options).textReturned
} catch (e) {
return null
}
}
function alert(text, informationalText) {
var options = { }
if (informationalText) options.message = informationalText
app.displayAlert(text, options)
}
function confirm(text) {
try {
app.displayDialog(text)
return true
} catch (e) {
return false
}
}
function executeTask(task) {
task.item.name = task.to
}
@JMichaelTX
Copy link

I'm not sure who wrote this script, but I first want to thank him/her for sharing. Much appreciated.

To deal with the issue above (you can expect a lot of JXA newbees), may I suggest:
(1) Add a section in the header comments for "How to Use"
(2) ADD a user selection validation test, and alert the user if no files have been selected in the Finder, and advise him/her that is required before running the script.
(3) You could also run the chooseFile method if the user does not make and Finder selections:

chooseFile
[withPrompt: text] : the prompt to be displayed in the dialog box
[ofType: list of text] : a list of file types or type identifiers. Only files of the specified types will be selectable.
[defaultLocation: alias] : the default file location
[invisibles: boolean] : Show invisible files and folders? (default is false)
[multipleSelectionsAllowed: boolean] : Allow multiple items to be selected? (default is false)
[showingPackageContents: boolean] : Show the contents of packages? (Packages will be treated as folders. Default is false.)
→ alias : the chosen file

@centurionjosephian
Copy link

I think you are already solved. But also if you need more facility with the batch name files- than kindly search on google by this keyword- BatchRenameFiles Tool. You will get the solve. I hope you will become happy by using the software of BatchRenameFiles Tool.

Thanks
Jonathan F.

@chrisgrieser
Copy link

Hi, I just stumbled upon this is snippet and it is truly awesome.

Would it be okay if I used it in my own (open source, non-commercial) project, of course with crediting? ( https://github.com/chrisgrieser/finder-vim-mode )

@dtinth
Copy link
Author

dtinth commented Jul 28, 2023

please feel free! @chrisgrieser

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment