Search code examples
zcat

Zcat multiple compressed files in a for loop


Im fairly new to bash scripting and i've been searching here in stackoverflow for an answer that will match what im looking for but cant find an exact match.. apologies if this has already been answered.

I have multiple folders that has multiple compressed files, some are gzip extension , some doesnt have extension.

The only way Ive been able to see the content of the compressed file is by doing

zcat filename.gzip > filename

My goal is to create a for loop that will :

  1. zcat all files and output it to a new file & add an identifier at the end, something like "-read"
  2. delete the compressed file

Thank you!


Solution

  • To decompress all files that gzip would handle using find, basename and a while loop:

    find . -type f | while read f; do
        set -e # You should probably always script with set -e
               # This will cause the subshell to stop on errors.
        zcat < "$f" > "$f-new" || continue
        rm "$f"
    done
    

    This should also handle any weird quoting that comes up. The while loop will run in a subshell, and set -e will set the stop on error option in it so that if there's an error with either the zcat or the rm it won't keep plowing ahead destroying everything in sight.