Search code examples
bashshellzip

how to zip files (with pattern) from another zip archive without extracting in linux


is there any way to "copy" all "**/bin/*.o" from org.zip file into new.zip without extract the org.zip.

org.zip:

$ unzip -l org.zip
Archive:  org.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
        0  04-24-2023 20:13   org/
        8  04-24-2023 20:06   org/c.c
        0  04-24-2023 20:00   org/bin/
       12  04-24-2023 20:02   org/bin/a.o         <- wanted
       12  04-24-2023 20:05   org/bin/b.o         <- wanted
       12  04-24-2023 20:03   org/bin/c.o.        <- wanted
        8  04-24-2023 20:06   org/a.c
        8  04-24-2023 20:06   org/b.c
        0  04-24-2023 19:59   org/debug/
       14  04-24-2023 20:03   org/debug/a.o
       14  04-24-2023 20:03   org/debug/b.o
       14  04-24-2023 20:03   org/debug/c.o
---------                     -------
      102                     12 files

# wanted files
$ unzip -Z1 org.zip  "**/bin/*.o"
org/bin/a.o
org/bin/b.o
org/bin/c.o

I was extract all wanted files into a "tmp" file, and compress again, and remove tmp folder finally ( as below ):

$ unzip -q -o org.zip '**/bin/*.o' -d ./tmp
$ ( cd ./tmp && zip -q -r - . ) > new.zip
$ rm -rf ./tmp

$ unzip -l new.zip
Archive:  new.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
        0  04-24-2023 20:20   org/
        0  04-24-2023 20:20   org/bin/
       12  04-24-2023 20:02   org/bin/a.o
       12  04-24-2023 20:05   org/bin/b.o
       12  04-24-2023 20:03   org/bin/c.o
---------                     -------
       36                     5 files

since both unzip and zip support stream, is there elegant way to handle it ? something like:

$ unzip -Z1 org.zip "**/bin/*.o" | xargs unzip -p -o org.zip | < ... how to zip ... >

Solution

  • Use zip with the --copy/-U flag like so:

    zip org.zip '**/bin/*.o' -U -O new.zip