#!/bin/env lua -- Basic mass file renamer using osx and -- standard Lua gsub(). -- -- SYNOPSIS: -- rename.lua [directory] -- -- Renames every file inside a directory (defaults to current directory). -- Trimmed down but functional and useful variant of util-linux rename(1). -- -- Example uses: -- lua rename.lua 'something' 'something_else' -- lua rename.lua '(%w+).lua' '%1.lua.bk' src -- -- Author: Lorenzo Cogotti, The DoubleFourteen Code Forge local io = require 'io' local osx = require 'osx' local write = io.write local dir = osx.dir local sep = osx.sep local ENOENT = 2 -- errno value for No such file or directory -- Read command line arguments local pattern = assert(select(1, ...), "Missing filename pattern argument") local repl = assert(select(2, ...), "Missing filename replacement argument") local path = select(3, ...) or "." -- Rename en-masse for filename in dir(path) do local newfilename = filename:gsub(pattern, repl, 1) if filename ~= newfilename then local from = path..sep..filename local to = path..sep..newfilename -- Refuse to overwrite files local buf, err, code = osx.stat(to) if buf then error(filename..": File '"..to.."' exists, refusing to overwrite.") end if code ~= ENOENT then -- Anything but "file does not exist" is dangerous, so bail out error(err) end -- Print a nice message and rename things write(from, ' -> ', to, '\n') assert(osx.rename(from, to)) end end