Find zip files and unzip into directory based on zip file name in linux

This command is a neat way to automate extracting multiple zip files into directories named after the files themselves. It avoids the need to unzip files manually one by one, which is particularly useful in large directories or complex file structures.

find . -iname '*.zip' -exec sh -c 'unzip "{}" -d "${1%.*}"' _ {} \;

Explanation:

  1. find .
    • The find command searches through directories recursively, starting from the current directory (.). It looks for files that match specific criteria.
  2. -iname '*.zip'
    • This option tells find to look for files with names ending in .zip. The -iname flag makes the search case-insensitive, meaning it will match .zip, .ZIP, or any other case combination.
  3. -exec
    • The -exec option allows you to run a command on each file that find locates. In this case, it runs a shell script to unzip the files.
  4. sh -c 'unzip "{}" -d "${1%.*}"' _ {}
    • sh -c runs the specified shell command. Here’s what this part does:
      • 'unzip "{}" -d "${1%.*}"': This is the actual unzipping command. unzip extracts the contents of the zip file ("{}" refers to the zip file found by find).
      • -d "${1%.*}": This specifies the target directory where the file should be extracted. The syntax ${1%.*} removes the .zip extension from the filename to use the base name of the zip file as the folder name. For example, if the zip file is example.zip, it will create a folder example to extract the contents into.
      • The first underscore (_) is a placeholder used by sh -c to refer to the next argument ({}), which is the zip file path that find passes to the command.
  5. {} \;
    • {} represents each file found by find, and \; terminates the -exec command.

Example:

Suppose you have the following structure:

/home/user
├── folder1
│ └── file1.zip
├── folder2
│ └── file2.ZIP

Running the command will:

  • Find file1.zip and file2.ZIP.
  • Extract the contents of file1.zip into a folder named file1 and file2.ZIP into a folder named file2.

Published by

Rich

Just another IT guy.

Leave a Reply

Your email address will not be published. Required fields are marked *