Skip to content

Instantly share code, notes, and snippets.

@AlexxNica
Forked from dtinth/README.md
Created January 2, 2018 12:56
Show Gist options
  • Save AlexxNica/33d7435e8d705a884c92982532733bc4 to your computer and use it in GitHub Desktop.
Save AlexxNica/33d7435e8d705a884c92982532733bc4 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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment