How can you compress all files in a directory that contain the word “compress” anywhere within its contents?
1 Answer
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
POSIX.)
-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
POSIX.)
-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.