LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Bash to group files by name and zip them (https://www.linuxquestions.org/questions/programming-9/bash-to-group-files-by-name-and-zip-them-4175675527/)

Dareios 05-19-2020 10:07 AM

Bash to group files by name and zip them
 
Hello,

I am looking for a way to go through a folder containing image files and ZIP them based on a substring. I started doing this using Applescript and Automator, but this was a very slow process. I came across the following Bash command

Code:

for i in *.JPG; do  zip "${i%.*}.zip" "${i%.*}".*; done
which zips each file individually. And I came across this command

Code:

for q in *_*.JPG; do mkdir -p "${q%_*}"; mv "$q" "${q%_*}"; done
The latter makes folders based on the common denominator.

As a programming newbie, what can I change in the ZIP command to achieve grouping the files and zipping them. The file names consist of an object number, following by underscore and a running number which may be up to three digits depending on the files concerning a specific object number (e.g., XYZ04999_01.jpg, XYZ04999_02.jpg, XYZ04999_03.jpg, etc.).

I'd be grateful for some help.

Thank you!

Turbocapitalist 05-19-2020 10:23 AM

A slight variant would be the standard tar archive:

Code:

for q in *_*.jpeg; do
        tar --append -vf "${q%_*}.tar" ${q}
done
gzip *.tar

The % there is part of parameter substitution and strips away the underscore and everything else to the end of the string. If that does not build the name you want then you can try a different method or build up a variable using several methods before passing it to tar.

shruggy 05-19-2020 12:24 PM

FYI, zip works like tar -append by default adding new files to an existing archive if specified on the command line, so the tar line above could be rewritten as
Code:

zip "${q%_*}.zip" ${q}

ondoho 05-19-2020 03:11 PM

A side issue: JPGs are already compressed; zipping a group of them together might be useful, but it will compress only marginally.


All times are GMT -5. The time now is 10:17 PM.