Created
December 17, 2022 02:18
-
-
Save L-Steinmacher/e338b03425d5f30b062cff3b001dc064 to your computer and use it in GitHub Desktop.
To be used with Script Kit to rename a batch of files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Name: rename ordered files | |
// Author: Lucas Steinmacher | |
// Description: renames a batch of ordered files with a prefix that you supply and starting at a given index that you supply | |
import "@johnlindquist/kit" | |
import fs from "fs" | |
// Note: Dropping one or more files returns an array of file information | |
// Dropping text or an image from the browser returns a string | |
let fileInfos = await drop() | |
cd(path.dirname(fileInfos[0].path)); | |
let startInput = await arg("whats the number of the first file?") | |
let filenamePrefix = await arg("whats the prefix of the files?") | |
// For debugging only | |
dev(iterateOverFileInfo(fileInfos, startInput, filenamePrefix)) | |
function iterateOverFileInfo(fileInfos, start, fileNamePrefix) { | |
// This array is for debugging only and holds the [newFileName, oldFileName] | |
let newFileNames = []; | |
// memoize the names with their correct number in case the files are out of order | |
let fileNameDict = {}; | |
let i = start; | |
fileInfos.forEach(fileInfo => { | |
let curFileSuffix = fileInfo.name.slice(-4); | |
let curFileName = fileInfo.name.slice(0, -4); | |
if (!(curFileName in fileNameDict)) { | |
fileNameDict[curFileName] = i; | |
i++; | |
} | |
const newFileName = `${fileNamePrefix}-part${fileNameDict[curFileName]}${curFileSuffix}` | |
fs.rename(fileInfo.name, newFileName, (e) => console.error(e.message)) | |
newFileNames.push([newFileName, fileInfo]) | |
}) | |
return newFileNames; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment