Gzip and rename (remove .gz extension) all files except images and PDFs?

I am able to gzip every file in a directory (mydirectory) using the command:

gzip --suffix .gz --recursive mydirectory

But...

  1. I don't want the images (.ico, .jpg, .png, .gif) and PDFs (.pdf) files within the directory to be gzipped.

  2. And those files that are gzipped have the .gz extension. I don't want that. For example, I'd like the gzipped index.html file be index.html itself, and NOT index.html.gz.

So, how do I do this, optimally/efficiently?


Here's how I am doing this now (a pretty lengthy process).

Compress all files in mydirectory but don't delete/replace original files:

cd ~/mydirectory
find . -type f | \
while read -r x
do gzip -c -9 "$x" > "$x.gz"
done

Remove all gzipped image and PDF files:

find . -type f -iname "*.ico.gz" -exec rm -f {} \;
find . -type f -iname "*.jpg.gz" -exec rm -f {} \;
find . -type f -iname "*.png.gz" -exec rm -f {} \;
find . -type f -iname "*.gif.gz" -exec rm -f {} \;
find . -type f -iname "*.pdf.gz" -exec rm -f {} \;

Rename the existing gzipped files, essentially removing the .gz extension from their name:

cd
for f in `find mydirectory -iname '*.gz'`; do mv $f ${f%.gz}
done

What we pretty much have now are gzipped text files (.html, .xml, .css, .js) without .gz extension, and uncompressed/un-gzipped images and PDFs.

1 Answer

Step 1: make a backup. Then use find to filter your files and run gzip and then move the file back to the original filename:

find -type f -not \( -iname '*.ico' -or -iname '*.jpg' -or -iname '*.png' -or -iname '*.gif' \) -exec gzip "{}" \; -exec mv "{}.gz" "{}" \;

This is a destructive command so please be careful. Remove the -exec... commands to begin with to make sure it's only selecting files you want to compress.

4

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like