Combine files by name and zip

automatorbashscriptzip

How can I automatically ZIP files with same file names (different extensions) into one ZIP?

For example I have four files

  • king.jpg
  • king.txt
  • queen.jpg
  • queen.txt

which would led to

  • king.zip (containing king.jpg and king.txt)
  • queen.zip (containing queen.jpg and queen.txt)

Best Answer

You can easily do this with a short bash snippet.

p=SOME.CRAZY.STUFF
for i in *; do
    f="${i%.*}"
    if [[ "$p" != "$f" ]]; then
        zip "$f" "$f".*
    fi
    p="$f"
done

If you are not familiar with Terminal/bash and don't plan to use this too often, you can do the following to use it:

  • create a folder where you move all your kings and queens to (and nothing else)
  • open Terminal, type cd followed by a space, drag the folder you've just created into the Terminal window (release the mouse button once a green cross appears) and press Enter
  • type p=SOME.CRAZY.STUFF followed by Enter
  • type (or even better copy/paste)

    for i in *; do f="${i%.*}"; if [[ "$p" != "$f" ]]; then zip "$f" "$f".*; fi; p="$f"; done
    

    again followed by Enter

  • (assuming no error message etc was displayed) quit Terminal again