I have a directory that consists of many subdirectories, and each subdirectory contains different files such as:

Directory All contains subdirectories A, B, C, and D. Each subdirectory contains files such as:

A (Run1.csv, Run4.csv)
B (Run2.csv, Run3.csv)
C (Run1.csv, Run3.csv)
D (Run2.csv, Run4.csv)

As you can see, each file has different duplicates in different subdirectories. For example, Run1.csv in folder A has different data from Run1.csv in folder C.

What I want to do is that I want to zip a specific run file, for example, I want to zip all the files of run2. I used the following commands:

zip run2.zip All Run2.csv 

zip run2.zip Run2.csv 

But none of them works.

How can I fix that?


You can use bash Pathname Expansion as follows:

zip run2.zip */Run2.csv

*/Run2.csv matches every file called Run2.csv in any subdirectory. If you have very many files that match the glob, this fails because of the shell’s ARG_MAX limit. To work around that, use:

printf '%s\0' */Run2.csv | xargs -0 zip run2.zip

This uses the builtin printf to build up a zero-delimited list of the matching files and pipes it to xargs, which calls zip as often as necessary. As add is zip’s default mode, it updates the archive adding the files to it.

If you need to dig further into an unknown or changing number of subdirectories, set bash’s globstar option with

shopt -s globstar

and use:

zip run2.zip **/Run2.csv  # or respectively
printf '%s\0' **/Run2.csv | xargs -0 zip run2.zip

**/Run2.csv matches every file called Run2.csv in any subdirectory recursively.

Further reading

  • If youre digging further, find might be a good option – D. Ben Knoble Apr 15 '19 at 16:37
  • 1
    @D.BenKnoble yes, but I left that to Romeo Ninov for his answer and helped him build the find command line. :) – dessert Apr 15 '19 at 17:26

you can use something like to search and archive all (for example) Run2.csv files:

zip run2.zip `find . -name Run2.csv`

By suggestion if OP expect special characters (like space) in file/directories names can use command like:

find . -name Run2.csv -exec zip run2.zip {} +

Try this for finding files and zip them in separate files :

find . -name Run2.csv -print | zip Run2.zip -@
  • This fails if any of the file or directory names contain whitespaces, you could use … -print0 | xargs -0 zip Run2.zip instead. – dessert Apr 15 '19 at 11:19

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.