I want to compress files individually with the particular pattern. For example, I have directory as below :


I want to compress all the files having extension .1 inside /log recursively.

The result will look like

  • So you also need to rename the files as you go...? Otherwise file.1 would be compressed as file.1.gz, etc. – roaima Apr 17 '18 at 10:57
  • 2
    And do you really have the /log/log1/-/ and /log/log2/-/ directories? – terdon Apr 17 '18 at 11:06

find + bash solution:

find /log -type f -name "*.1" -exec bash -c 'gzip -nc "$1" > "${1:0:-2}.gz"; rm "$1"' _ {} \;

gzip options:

  • -n - when compressing, do not save the original file name and time stamp by default
  • -c - write output on standard output; keep original files unchanged

${1:0:-2} - bash's slicing; get filepath with the last 2 characters truncated


You could do something like:

find /log -name '*.1' -type f -exec sh -c '
  for file do
    gzip "$file" && mv -i "$file.gz" "${file%.*}.gz"
  done' sh {} +

We use the gzip file && mv -i file.gz newfile as opposed to gzip < file > newfile && rm -f file to benefit from gzip's ability to preserve some of the metadata into the compressed file and for mv -i's better ability to deal with conflicts.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.