36

I have several directories that look like this:

dir1/
  |_foo.txt
  |_bar.txt
dir2/
  |_qux.txt
  |_bar.txt

For each of this directory I want to compress the files inside it into *.gz format then delete the uncompressed ones. So finally we hope to get something like this:

 dir1/
   |_foo.gz
   |_bar.gz
 dir2/
   |_qux.gz
   |_bar.gz

Is there a simple Unix way to do it?

neversaint
  • 60,904
  • 137
  • 310
  • 477

3 Answers3

50
gzip */*.txt

But the extension for each file will be .txt.gz, as gzip uses it to know the original filename.

Juliano
  • 39,173
  • 13
  • 67
  • 73
13

gzip -r dir1 dir2

vovick
  • 298
  • 1
  • 8
10

The following will work even if you have sub-directories. E.g. dir1/dir2/.../foo.txt

find . -type f -name "*.txt" -exec gzip {} \;
dogbane
  • 266,786
  • 75
  • 396
  • 414
  • 3
    You could also do `gzip ./**/*.txt`, which recurses into all directories within the current one, gzipping all text files, and deleting the originals. – thekingoftruth Oct 13 '16 at 05:32