Search code examples
backupgzipzcat

zcat a file, output its contents to another file based on original filename


I'm looking to create a bash/perl script in Linux that will restore .gz files based on filename:

_path_to_file.txt.gz
_path_to_another_file.conf.gz

Where the underscores form the directory structure.. so the two above would be:

/path/to/file.txt
/path/to/another/file.conf

These are all in the /backup/ directory..

I want to write a script that will cat each .gz file into its correct location by changing the _ to / to find the correct path - so that the contents of _path_to_another_file.conf.gz replaces the text in /path/to/another/file.conf

zcat _path_to_another_file.conf.gz > /path/to/another/file.conf

I've started by creating a file with the correct destination filenames in it.. I could create another file to list the original filenames in it and have the script go through line by line?

ls /backup/ |grep .gz > /backup/backup_files && sed -i 's,_,\/,g' /backup/backup_files && cat /backup/backup_files

Whatcha think?


Solution

  • Here's a Bash script that should do what you want :

    #!/bin/bash
    for f in *.gz; do
        n=$(echo $f | tr _ /)
        zcat $f > ${n%.*}
    done
    

    It loops over all files that end with .gz, and extracts them into the path represented by their filename with _ replaced with /.