gzip all files with specific extensions

I'm trying to gzip all files on ubuntu that have the file extension .css, .html or .js. in a top directory and all subdirectories. I want to keep the original files and overwrite the .gz file, if already existing.

So when I have n files, I want to keep these n files and create additional n archive files. Not just one.

My try was to run a script that looks like this:

gzip -rkf *.css
gzip -rkf *.html
... one line for each file extension

First: I need to have one line in that script for each file extension I want to gzip. That's ok, but I hope to find a better way

Second and more important: It does not work. Although -r should do the job, the subdirectories are unchanged. The gzip file is only created in the top directory.

What am I missing here?

Btw: The following is a bug in the verbose output, right? When using -k and -v option

-k, --keep        keep (don't delete) input files
-v, --verbose     verbose mode

The verbose output says it replaces the file, although "replace" means that the original file does not exist after the replace. Anyway, THis is only the output thing.

$ ls
  index.html      subdir1  testfile      testfile.css.gz
  javaclass.java  subdir2  testfile.css
$ gzip -fkv *.css
  testfile.css:   6.6% -- replaced with testfile.css.gz
$ ls
  index.html      subdir1  testfile      testfile.css.gz
  javaclass.java  subdir2  testfile.css

Solution 1:

I would use

find /path/to/dir \( -name '*.css' -o -name '*.html' \) -exec gzip --verbose --keep {} \;

Change name to iname if you want to match the extensions case-insensitively (i.e. include .CSS and/or .HTML extensions). You can omit the /path/to/dir if you want to start the recursive search from the current directory.

Solution 2:

you can do that with a for loop to find every file then compress it:

for i in `find | grep -E "\.css$|\.html$"`; do gzip "$i" ; done