53

I tried to search files and zip them with the following commmand

find . regexpression -exec zip {} \;

however it is not working. How can i do this?

Sebas
  • 21,192
  • 9
  • 55
  • 109
LOGAN
  • 1,025
  • 2
  • 10
  • 14

3 Answers3

117

The command you use will run zip on each file separately, try this:

find . -name <name> -print | zip newZipFile.zip -@

The -@ tells zip to read files from the input. From man zip(1),

-@ file lists. If a file list is specified as -@ [Not on MacOS], zip takes the list of input files from standard input instead of from the command line.

jpaugh
  • 6,634
  • 4
  • 38
  • 90
iabdalkader
  • 17,009
  • 4
  • 47
  • 74
  • can i remove the files in this command which are being zipped as well??? or i will have to give another command like find . -name -exec rm -rf {} \; to remove zipped files – LOGAN Nov 05 '12 at 15:27
  • @LOGAN the easiest way would be to do that, to run another command, but maybe there's a better way to do it, you should ask a new question for that. – iabdalkader Nov 05 '12 at 15:28
  • 3
    Just tried on a Mac, works like a charm. I guess you can remove the disclaimer – SGD Dec 04 '15 at 15:01
  • 1
    That disclaimer comes from the manpage, even on macOS, but indeed the `-@` option works. – rgov May 02 '19 at 21:44
  • Based on that It's how I zip changes `find . -cmin -400 -print | zip newZipFile.zip -q@`. – Hebe Aug 28 '20 at 00:17
  • One may omit `-print` as by default `find` prints found files. – ivan_onys Feb 06 '23 at 15:19
22

Your response is close, but this might work better:

find -regex 'regex' -exec zip filname.zip {} +

That will put all the matching files in one zip file called filename.zip. You don't have to worry about special characters in the filename (like a line break), which you would if you piped the results.

Dan Jones
  • 1,337
  • 11
  • 22
  • do what? with the + sign – aliopi Jul 28 '17 at 20:32
  • 6
    @aliopi The + means to replace the {} with all of the filenames, rather than execute the command once for each file. – Dan Jones Jul 28 '17 at 21:16
  • 1
    If you perform a search in an external directory, the result may be something like `home/path/file`. in that case it is necessary to use `zip -j` more info here [create-zip-ignore-directory-structure](https://stackoverflow.com/questions/9710141/create-zip-ignore-directory-structure) – Jasp402 Oct 23 '19 at 23:50
16

You can also provide the names as the result of your find command:

zip name.zip `find . -name <name> -print`

This is a feature of the shell you are using. You can search for "backticks" to determine how your shell handles this.

jheddings
  • 26,717
  • 8
  • 52
  • 65