Bash – Zipping Files Two by Two

bashcommand linewildcardszip

I have a directory that has 800 files like this:

file1.png
file1@2x.png

file2.png
file2@2x.png

file3.png
file3@2x.png

... etc

I need to create zip files like this

file1.zip (containing file1.png and file1@2x.png)
file2.zip (containing file2.png and file2@2x.png)
file3.zip (containing file3.png and file3@2x.png)

Is there a magic command I can use to do that?

Best Answer

If always there are two, is simple:

for f in file+([0-9]).png; do zip "${f%png}zip" "$f" "${f/./@2x.}"; done

Note that the above will work as is from the command line. If you intend to use it in a script, put shopt -s extglob somewhere before that line. (extglob is enabled by default only in interactive shells.)

In old bash not handling extended patterns this ugly workaround will work, but better change the logic as suggested in another answer by Leonid:

for f in file[0-9].png file*[0-9][0-9].png; do zip "${f%png}zip" "$f" "${f/./@2x.}"; done
Related Question