Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to gzip all files in all sub-directories in bash

I want to iterate among sub directories of my current location and gzip each file seperately. For zipping files in a directory, I use

for file in *; do gzip "$file"; done

but this can just work on current directory and not the sub directories of the current directory. How can I rewrite the above statements so that It also zips the files in all subdirectories?

like image 296
Farshid Avatar asked Apr 28 '12 13:04

Farshid


People also ask

How do I recursively gzip?

How to recursively compress files using gzip? To recursively compress files, use the -r command line option. This option, as the name suggests, will compress files in the main directory as well as all subdirectories. So you can see that all files - whether in main directory or subdirectory - were compressed.

Can you gzip multiple files at once?

To compress multiple files at once using gzip , we use the gzip command with -d option followed by file names to be decompressed separated by a space.


3 Answers

No need for loops or anything more than find and gzip:

find . -type f ! -name '*.gz' -exec gzip "{}" \;

This finds all regular files in and below the current directory whose names don't end with the .gz extension (that is, all files that are not already compressed). It invokes gzip on each file individually.


Edit, based on comment from user unknown:

The curly braces ({}) are replaced with the filename, which is passed directly, as a single word, to the command following -exec as you can see here:

$ touch foo
$ touch "bar baz"
$ touch xyzzy
$ find . -exec echo {} \;

./foo
./bar baz
./xyzzy
like image 145
Adam Liss Avatar answered Sep 29 '22 23:09

Adam Liss


I'd prefer gzip -r ./ which does the same thing but is shorter.

like image 42
Supernormal Avatar answered Oct 01 '22 23:10

Supernormal


find . -type f | while read file; do gzip "$file"; done
like image 23
Tim Pote Avatar answered Sep 29 '22 23:09

Tim Pote