Skip to content

Instantly share code, notes, and snippets.

@dtinth
Last active December 20, 2023 15:06
Show Gist options
  • Star 28 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • 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
}
@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