2022-12-15 09:35:18 +01:00
|
|
|
#!/bin/env lua
|
|
|
|
-- Basic mass file renamer using osx and
|
|
|
|
-- standard Lua gsub().
|
|
|
|
--
|
|
|
|
-- Renames every file inside a directory.
|
|
|
|
-- A trimmed down but functional and useful
|
|
|
|
-- variant of util-linux rename(1)
|
|
|
|
--
|
|
|
|
-- 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 "."
|
|
|
|
|
2022-12-15 09:38:16 +01:00
|
|
|
-- Rename en-masse
|
2022-12-15 09:35:18 +01:00
|
|
|
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
|
|
|
|
|
2022-12-15 09:38:16 +01:00
|
|
|
-- Refuse to overwrite files
|
2022-12-15 09:35:18 +01:00
|
|
|
local buf, err, code = osx.stat(to)
|
|
|
|
if buf then
|
|
|
|
error(filename..": File '"..to.."' exists, refusing to overwrite.")
|
|
|
|
end
|
|
|
|
if code ~= ENOENT then
|
2022-12-15 09:38:16 +01:00
|
|
|
-- Anything but "file does not exist" is dangerous, so bail out
|
2022-12-15 09:35:18 +01:00
|
|
|
error(err)
|
|
|
|
end
|
|
|
|
|
2022-12-15 09:38:16 +01:00
|
|
|
-- Print a nice message and rename things
|
2022-12-15 09:35:18 +01:00
|
|
|
write(from, ' -> ', to)
|
2022-12-15 09:38:57 +01:00
|
|
|
assert(osx.rename(from, to))
|
2022-12-15 09:35:18 +01:00
|
|
|
end
|
|
|
|
end
|