asfman
asfman

Reputation: 521

linux how to add a file to a specific folder within a zip file

i know how to add a file to the root folder within a zip file:

zip -g xxx.apk yyy.txt

but i've no idea how to specify a particular folder within a zip file

Upvotes: 40

Views: 45583

Answers (4)

jcollado
jcollado

Reputation: 40424

If you need to add the file to the same folder as in the original directory hierarchy, then you just need to add the full path to it:

zip -g xxx.zip folder/file

Otherwise, probably the easiest way to do that is to create the same layout you need in the zip file in a temporary directory.

Upvotes: 40

test30
test30

Reputation: 3654

I have expended a little @"that other guy" solution

Go to console, press ctrl+x,ctrl+e, paste there

( cat <<-'EOF'
#!/bin/bash
if [ $# -lt 3 ]; then
echo my_zip.zip your/existing/file_to_add.xml directory_in_zip/file_to_add.xml
exit
fi

python -c '
import zipfile as zf, sys
z=zf.ZipFile(sys.argv[1], "a")
z.write(sys.argv[2], sys.argv[3])
z.close()' $1 $2 $3
EOF
) > /tmp/zip-extend && chmod +x /tmp/zip-extend

then run /tmp/zip-extend my_zip.zip your/existing/file_to_add.xml directory_in_zip/file_to_add.xml

Example:

cd /tmp
touch first_file.txt
zip my_zip.zip first_file.txt
unzip -l my_zip.zip
mkdir -p your/existing
touch your/existing/file_to_add.xml
/tmp/zip-extend my_zip.zip your/existing/file_to_add.xml directory_in_zip/file_to_add.xml
unzip -l my_zip.zip
cd -

Result:

Archive:  my_zip.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
        0  2013-12-17 15:24   first_file.txt
        0  2013-12-17 15:24   directory_in_zip/file_to_add.xml
---------                     -------
        0                     2 files

Upvotes: 3

that other guy
that other guy

Reputation: 123750

To elaborate on @Ignacio Vazquez-Abrams answer from a year ago, you can use a lower level library, such as the one that comes with Python:

#!/bin/bash
python -c '
import zipfile as zf, sys
z=zf.ZipFile(sys.argv[1], "a")
z.write(sys.argv[2], sys.argv[3])
z.close()
' myfile.zip source/dir/file.txt dir/in/zip/file.txt

This will open myfile.zip and add source/dir/file.txt from the file system as dir/in/zip/file.txt in the zip file.

Upvotes: 11

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799570

Info-ZIP cannot do this. You will need to write a script or program in a language that has lower-level access to zip files.

Upvotes: 4

Related Questions