Lua Script for Selective File Backup Based on Extension

Lua script for selective file backup by extension, copying only specified file types from source to destination with LuaFileSystem support.

Brief Introduction

Lua Script for Selective File Backup Based on Extension (lua)
DESCRIPTION:
This Lua script performs a selective backup of files from a source directory to a destination directory, copying only files that match one or more specified extensions. It is useful to save only certain types of files, for example only images or documents, avoiding copying unnecessary files.

ADDITIONAL NOTES:
To run this script you need to have Lua installed and the LuaFileSystem (lfs) library. On Linux systems it can be installed with 'luarocks install luafilesystem'. The script handles creating the destination directory if it does not exist and overwrites files with the same name. It is possible to extend the script to include exclusions or incremental backups.

EXPLANATIONS:
- The 'file_extension' function extracts the file extension to compare it with the desired ones.
- The 'copy_file' function opens the source file in binary read mode and copies it byte by byte to the destination file.
- The 'backup_files' function iterates all files in the source directory, checks the extension and copies only those that match.
- The creation of the destination directory is handled if it does not exist, using 'lfs.mkdir'.
- Comments in the code are in Italian to facilitate understanding.

Example Code: lua

-- Lua script for selective file backup based on extension

local lfs = require("lfs") -- Import the LuaFileSystem library

-- Function to get the file extension (in lowercase)
local function file_extension(filename)
    return filename:match("%.([^.]+)$") and filename:match("%.([^.]+)$"):lower() or ""
end

-- Function to copy a file from src to dest
local function copy_file(src, dest)
    local src_file = io.open(src, "rb") -- opens the source file in binary mode
    if not src_file then
        return false, "Unable to open source file: " .. src
    end
    local dest_file = io.open(dest, "wb") -- opens/creates the destination file
    if not dest_file then
        src_file:close()
        return false, "Unable to create destination file: " .. dest
    end
    
    local content = src_file:read("*all") -- reads all the content
    dest_file:write(content) -- writes the content to the destination file

    src_file:close()
    dest_file:close()
    return true
end

-- Main function to perform selective backup
-- src_dir: source directory
-- dest_dir: destination directory
-- extensions: array of extensions to include (without dot, e.g. {"txt", "jpg"})
local function backup_files(src_dir, dest_dir, extensions)
    -- Check if the source directory exists
    local attr = lfs.attributes(src_dir)
    if not attr or attr.mode ~= "directory" then
        error("Source directory does not exist or is not a directory: " .. src_dir)
    end

    -- Create the destination directory if it does not exist
    attr = lfs.attributes(dest_dir)
    if not attr then
        local ok, err = lfs.mkdir(dest_dir)
        if not ok then
            error("Unable to create destination directory: " .. err)
        end
    elseif attr.mode ~= "directory" then
        error("Destination exists but is not a directory: " .. dest_dir)
    end

    -- Iterate files in the source directory
    for file in lfs.dir(src_dir) do
        if file ~= "." and file ~= ".." then
            local full_path = src_dir .. "/" .. file
            local file_attr = lfs.attributes(full_path)
            if file_attr and file_attr.mode == "file" then
                local ext = file_extension(file)
                -- Check if the extension is among those to include
                for _, v in ipairs(extensions) do
                    if ext == v:lower() then
                        local dest_path = dest_dir .. "/" .. file
                        local ok, err = copy_file(full_path, dest_path)
                        if ok then
                            print("Backup completed for: " .. file)
                        else
                            print("Error backing up " .. file .. ": " .. err)
                        end
                        break
                    end
                end
            end
        end
    end
end

-- Usage example
local sorgente = "./dati_sorgente" -- source directory
local destinazione = "./backup" -- destination directory
local estensioni_da_backup = {"txt", "jpg", "png"} -- extensions to include

-- Perform the backup
backup_files(sorgente, destinazione, estensioni_da_backup)
×
×
×
Do you want to regenerate the answer?
×
Export chat
Choose export format
Generazione PDF in corso…
Allegati
×
You are about to close the chat and switch to the image generator. If you are not logged in, you will lose our chat. Do you confirm?
You are viewing a shared chat in temporary mode. It will not be saved.
×
Saved prompts
×
Private note
×
Label
×
Search all chats
×
Your insights
Analyzing…
×
AI Preferences
Assistant name 30
Answer length
AI model
Structured answers
Include examples
Use emojis
Guide me, don't solve Hints and questions instead of a ready answer
More settings →
×
Share this chat
Anyone opening this link can view the chat or add it to their profile as their own chat.
Note: the chat attachments will be shared too. Anyone who adds it will receive a copy of the files in their own folder.
Shared chat
Someone shared a chat with you. Do you want to just view it or add it to your chats?
Note: the chat attachments will be shared too. Anyone who adds it will receive a copy of the files in their own folder.
×

Saved messages

Loading...

×

Chat History

example-programs · CHAT HISTORY

Loading...

AI Preferences

×
  • BasicQuick and essential answers for study
  • MediumHigher quality for study and programming
  • AdvancedComplex reasoning and detailed analysis
Explain Steps

What do you need?

Software: Lua 5.3 or higher

Software: LuaFileSystem (lfs) library for filesystem operations

Configuration: specify the source and destination directories in the code

Configuration: define an array of file extensions to include in the backup

Operating system: script tested on Unix-like and Windows systems (path compatibility)

No specific hardware required