1

I have a folder working and its structure is something like this -

working/
  100/
      1/
      2/
      3/
  200/
      1/
      2/
      3/
  300/
      1/
      2/
      3/

And each of these 1 2 3 folders have around 1000 files.

I want to zip the files under the 1 2 3 folders separately. The zip should not contain their top directories. Put the zips wherever they are. Such as, if there are files foo1, foo2 and foo3 under folder 1 then it should form a zip under 1 which should just have the foo files.

  • 2
    What should happen if there are more than the 1000 files in a subdirectory? Or did you mean that you want a single zip per folder of all the files in that folder? – roaima Jan 28 '15 at 23:36
  • Is it enough for you tar -lzip --no-wildcards-match-slash -c -f arch.zip working/*/ ? – Costas Jan 29 '15 at 1:01
  • @roaima no, number of files don't matter. Yes I meant whatever you said the next. This - I want to zip the files under each of the 1 2 3 folders. Such as, if there are files foo1 foo2 and foo3 under folder 1 then it should form a zip under 1 which should just have the foo files. @Costas, i want to zip them strictly. You sure this'll work? – Chinmay Kunkikar Jan 29 '15 at 5:49
2

A simple loop will do the trick.

cd working
for dir in */*/; do
  [ -e "$dir/files.zip" ] ||   # skip directories where the zip already exists
  ( cd -- "$dir" && zip -r files.zip .)
done

Note that zip is smart enough to skip the zip file that is being built when recursing in that directory. Some other archiving programs would attempt to stuff the archive being built into the archive that's being built.

  • Awesome! But one thing. There is a zip called 'flashify.zip' which should go into the zip too. Also, I think there's need for maxdepth or something because there are folders under 1 2 3. Sorry for the inconvenience. – Chinmay Kunkikar Jan 30 '15 at 3:03
  • @ChinmayKunkikar If flashify.zip is in the directory then it'll be included in the zip, otherwise it won't be included, just like you specified in the question. If you want to include another file in the zip, you can add it, e.g. zip "$dir/files.zip" flashify.zip if flashify.zip is located in working. – Gilles Jan 30 '15 at 6:19
  • @ChinmayKunkikar What do you mean by “there's need for maxdepth” — do you mean that 100/1 and so on have subdirectories and that you don't want to include them in the zip? Then you can change zip -r files.zip . to zip -D files.zip * (this will omit dot files as well). Next time, include all your requirements in your question. – Gilles Jan 30 '15 at 6:21
  • Sorry, I simply didn't noticed the */*; . I got what I wanted. Thanks a lot. – Chinmay Kunkikar Jan 30 '15 at 10:39

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.