Question

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?

Was it helpful?

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 /.

OTHER TIPS

That's not necessarily an invertible mapping (what if the original file is named high_scores for instance? is that encoded specially, e.g., with double underscore as high__scores.gz?) but if you just want to take a name and translate _ to / and remove .gz at the end, sed will do it:

for name in /backup/*.gz; do
    newname=$(echo "$name" |
        sed -e 's,^/backup/,,' \
            -e 's,_,/,g' \
            -e 's/\.gz$//')
    echo "zcat $name > $newname"
done

Make sure it works right (the above is completely untested!) then take out the echo, leaving:

    zcat "$name" > "$newname"

(the quotes protect against white space in the names).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top