[examples/rename] Add mass file rename example.
This commit is contained in:
parent
2de1d642ec
commit
ba26f107da
|
@ -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
|
Loading…
Reference in New Issue