How can you compress all files in a directory that contain the word “compress” anywhere within its contents?

1 Answer 1


You can do:

cd directory
grep -Fl -Z compress | xargs -0 compress

and replace the second compress (the argument to xargs) with gzip with bzip2 or xz to get increasingly better compression on most files.

The -F option for grep does uses fixed strings, -l only lists the filenames of the matching files and -Z puts a zero byte between the filenames (so this handles spaces and newlines in filenames). xargs then hands this to compress as commandline arguments.

From man page for grep:

-F, --fixed-strings
       Interpret PATTERN as a  list  of  fixed  strings,  separated  by
       newlines,  any  of  which is to be matched.  (-F is specified by

-l, --files-with-matches
       Suppress  normal  output;  instead  print the name of each input
       file from which output would normally have  been  printed.   The
       scanning  will  stop  on  the  first match.  (-l is specified by

-Z, --null
       Output  a  zero  byte  (the  ASCII NUL character) instead of the
       character that normally follows a file name.  For example,  grep
       -lZ  outputs  a  zero  byte  after each file name instead of the
       usual newline.  This option makes the output  unambiguous,  even
       in the presence of file names containing unusual characters like
       newlines.  This option can  be  used  with  commands  like  find
       -print0,  perl  -0,  sort  -z, and xargs -0 to process arbitrary
       file names, even those that contain newline characters.
  • for gzip,cd directory grep -Fl -Z gzip | xargs -0 compress Or
    – Prady
    Feb 9, 2014 at 9:11
  • Or grep -Fl -Z compress | xargs -0 gzip
    – Prady
    Feb 9, 2014 at 9:11
  • @Prady The second one, I updated the answer. Sorry for being ambiguous
    – Timo
    Feb 9, 2014 at 9:14

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.