Is it possible to zip files one directory up with "zip"

14 views (last 30 days)
This creates file1.zip containing file2 and file3:
zip('file1',{'file2','file3'})
However, this creates file1.zip containing nothing:
zip('file1',{'../file2','../file3'})
Likewise, this creates file1.zip containing nothing:
zip('../file1',{'../file2','../file3'})
Is there a way to perform zip for files that are one or more directories up?
  1 Comment
Harishankar
Harishankar on 28 Feb 2024
Certainly! To zip files from directories that are one or more levels up, we can use a simple Bash script. Let’s break down the solution step by step:
  1. Zipping Subdirectories into Individual Zip Files: Suppose we have the following directory structure inside the parent directory /mydir:├── dir_1
│ ├── sub_dir_11
│ ├── sub_dir_12
│ └── sub_dir_13
├── dir_2
│ └── sub_dir_22
│ ├── sub_dir_22_1
│ ├── sub_dir_22_2
│ └── sub_dir_23_3
├── dir_3
│ └── sub_dir_31
├── dir_4
└── my_file.txt
Our goal is to create separate zip files for each subdirectory (dir_1, dir_2, dir_3, and dir_4). We’ll achieve this using the following Bash script:
#!/bin/bash
# Change to the primary directory
cd /mydir
# Iterate over subdirectories
for subdir in */; do
# Extract the subdirectory name
dirname=$(basename "$subdir")
# Zip the subdirectory into a unique .zip file
zip -r "$dirname.zip" "$subdir"
done
This script iterates over all subdirectories in /mydir and creates a zip file for each subdirectory. The -r flag ensures that all files and subdirectories within each subdirectory are included in the zip file. After running this script, you’ll have four zip files: dir_1.zip, dir_2.zip, dir_3.zip, and dir_4.zip1.
  1. Handling Nested Subdirectories: The above script won’t create zip files for nested subdirectories (e.g., sub_dir_11, sub_dir_12, etc.). To handle nested subdirectories, we’ll use a recursive approach. Here’s an updated script:#!/bin/bash
# Change to the primary directory
cd /mydir
# Find all subdirectories (including nested ones) and loop through them
find . -type d -print0 | while IFS= read -r -d '' subdir; do
# Extract the subdirectory name
dirname=$(basename "$subdir")
# Skip the primary directory itself
if [ "$dirname" != "." ]; then
# Zip the subdirectory into a unique .zip file
zip -r "$dirname.zip" "$subdir"
fi
done
This updated script uses the find command to list all subdirectories (including nested ones) and creates zip files for each of them. Now it will handle nested subdirectories as well1.
Remember to adjust the paths and directory names according to your specific use case. Happy zipping! 📁🔒

Sign in to comment.

Accepted Answer

Voss
Voss on 28 Feb 2024
Try this:
zip('file1',fullfile(pwd(),'..',{'file2','file3'}))

More Answers (0)

Categories

Find more on File Operations in Help Center and File Exchange

Tags

Products


Release

R2023b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!