lua-osx/examples/rename.lua

47 lines
1.3 KiB
Lua
Raw Normal View History

#!/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
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
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
error(err)
end
2022-12-15 09:38:16 +01:00
-- Print a nice message and rename things
write(from, ' -> ', to)
2022-12-15 09:38:57 +01:00
assert(osx.rename(from, to))
end
end