[examples/rename] Add mass file rename example.

This commit is contained in:
Lorenzo Cogotti 2022-12-15 09:35:18 +01:00
parent 2de1d642ec
commit ba26f107da
1 changed files with 42 additions and 0 deletions

42
examples/rename.lua Executable file
View File

@ -0,0 +1,42 @@
#!/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 "."
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
local buf, err, code = osx.stat(to)
if buf then
error(filename..": File '"..to.."' exists, refusing to overwrite.")
end
if code ~= ENOENT then
error(err)
end
write(from, ' -> ', to)
assert(osx.rename(filename, newfilename))
end
end