Unzipping folder in linux

Unzip files in particular directory or folder under Linux or UNIX

Q. I’m new to Linux command line. I’ve a command called unzip and a file called package.zip. I can extract file using command:
unzip package.zip

All files are extracted into current directory (it is making a directory called package). I want all files and subdirectory extracted into /opt directory. How do I extract files in /opt?

A. unzip command will list, test, or extract files from a ZIP archive, commonly found on MS-DOS systems. The default behavior (with no options) is to extract into the current
directory (and subdirectories below it) all files from the specified ZIP archive.

By default, all files and subdirectories are recreated in the current directory; the -d option allows extraction in an arbitrary directory (always assuming one has permission to write to the directory). This option need not appear at the end of the command line; it is also accepted before the zipfile specification (with the normal options), immediately after the zipfile specification, or between the file(s) and the -x option. The option and directory may be concatenated without any white space between them, but note that this may cause normal shell behavior to be suppressed.

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

For example extract package.zip into /opt, enter:
# unzip package.zip -d /opt
# cd /opt
# ls

If you want to rename package directory use mv command:
# mv package newname

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

How to Unzip a Zip File in Linux [Beginner’s Tutorial]

Last updated October 9, 2019 By Abhishek Prakash 9 Comments

Brief: This quick tip shows you how to unzip a file in Ubuntu and other Linux distributions. Both terminal and GUI methods have been discussed.

Zip is one of the most common and most popular way to create compressed archive files. It is also one of the older archive file format that was created in 1989. Since it is widely used, you’ll regularly come across a zip file.

In an earlier tutorial, I showed how to zip a folder in Linux. In this quick tutorial for beginner’s, I’ll show you how to unzip files in Linux.

Prerequisite: Verify if you have unzip installed

In order to unzip a zip archive file, you must have the unzip package installed in your system. Most modern Linux distributions come with uzip support but there is no harm in verifying it to avoid bad surprises later.

In Ubuntu and Debian based distributions, you can use the command below to install unzip. If it’s already installed, you’ll be notified about it.

Once you have made sure that your system has unzip support, it’s time to unzip a zip file in Linux.

You can use both command line and GUI for this purpose and I’ll show you both methods.

Unzip file in Linux command line

Using unzip command in Linux is absolutely simple. In the directory, where you have the zip file, use this command:

Читайте также:  Dota 2 вылетает mac os

You can also provide the path to the zip file instead of going to the directory. You’ll see extracted files in the output:

There is a slight problem with the above command. It will extract all the contents of the zip file in the current directory. That’s not a pretty thing to do because you’ll have a handful of files leaving the current directory unorganized.

Unzip to directory

A good practice is to unzip to directory in Linux command line. This way, all the extracted files are stored in the directory you specified. If the directory doesn’t exist, it will create one.

Now all the contents of the zipped_file.zip will be extracted to unzipped_directory.

Since we are discussing good practices, another tip you can use is to have a look at the content of the zip file without actually extracting it.

See the content of zip file without unzipping it

You can check the content of the zip file without even extracting it with the option -l.

Here’s a sample output:

There are many other usage of the unzip command in Linux but I guess now you have enough knowledge to unzip files in Linux.

Unzip files in Linux using GUI

You don’t always have to go to the terminal if you are using desktop Linux. Let’s see how to unzip in Ubuntu Linux graphically. I am using GNOME desktop here with Ubuntu 18.04 but the process is pretty much the same in other desktop Linux distributions.

Open the file manager and go to the folder where your zip file is stored. Right click the file and you’ll see the option “extract here”. Select this one.

Unlike the unzip command, the extract here options create a folder of the same name as the zipped file and all the content of the zipped files are extracted to this newly created folder. I am glad that this is the default behavior instead of extracting everything in the current directory.

There is also the option of ‘extract to’ and with that you can specify the folder where you want to extract the files.

That’s it. Now you know how to unzip a file in Linux. Perhaps you might also be interested in learning about using 7zip in Linux.

If you have questions or suggestions, do let me know in the comment section.

Like what you read? Please share it with others.

Источник

Примеры использования zip и unzip в linux

Сегодня я хотел сделать пост памятку по работе в Unix подобных системах с утилитами zip и unzip. Также рассмотреть несколько интересных команд, которые могут пригодиться для работы.

Установка zip и unzip:

В системе Debian/Ubuntu.

В системе Red Hat Linux/Fedora/CentOS.

Пример использования утилиты zip

Пример 1: Создания архива из указанных файлов и папок

Пример 2: Создания архива текущего каталога (архив создается без подкаталогов)

Пример 3: Создания архива включая все подкаталоги используем ключ -r

Создает архив без скрытых файлов/каталог это файлы/каталоги начинающиеся с .

Создает архив с скрытыми файлами и каталогами

Пример 4: Чтобы сжать быстро используйте -1, но для более лучшего сжатие используйте -9

Пример 5: Опция -x позволяет исключать файлы и каталоги из архива

Пример 6: Также опция -x позволяет исключать файлы и каталоги по шаблону

Таким способом я исключаю все каталоги заканчивающихся на ted и файлы расширения xml

Пример 7: Разбиваем архив на части с помощью опции -s

Также есть возможность указать опцию размера части архива в: k (KB), m (MB), g (GB), t (TB)

Пример 8: Задать пароль можно опцией -e или опцией -P .

Пример 9: Выбрать только указанные файлы/каталоги

Пример 10: Удаление файлов из созданного архива

Пример 11: Обновить содержимое созданного архива

Пример 11: Тихий режим (Полезно, например, в сценариях оболочки и фоновых задач)

Пример 12: Извлечь все содержимое архива

Пример 13: Извлечь все содержимое архива в указанную директорию

Пример 14: Показать содержимое архива

Пример 15: Извлечь конкретный файл из архива

Источник

How do I unzip multiple / many files under Linux?

The problem with multiple zip files on Linux

Assuming that you have four file in a /disk2/images/ directory as follows:

Let us verify it with the ls command:
$ ls
Sample outputs:

Читайте также:  Как обновить хром линукс

To unzip all files, enter:
$ unzip *.zip
Sample outputs:

Above error indicate that you used the unzip command wrongly. It means extract invoices.zip, pictures.zip, and visit.zip files from inside the data.zip archive. Your shell expands the command ‘unzip *.zip’ it as follows:
unzip data.zip invoices.zip pictures.zip visit.zip
The solution is pretty simple when you want to unzip the file using the wild card; you have two options as follows.

#1: Unzip Multiple Files Using Single Quote (short version)

The syntax is as follows to unzip multiple files from Linux command line:

Type the following command as follows:
$ cd /disk2/images/
$ unzip ‘*.zip’
$ ls -l

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Note: *.zip is put in between two single quotes so that shell will not recognize it as a wild card character.

#2: Unzip Multiple Files from Linux Command Line Using Shell For Loop (Long Version)

See also

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

# If files are password protected, and we are not sure which password

for Z_FILE in *.zip; do
for PASSWD in [ pass123, PASS123, abc123, ABC123 ]; do
unzip -P $PASSWD $Z_FILE;
if [ $? = 0 ]; then # successful unzip
break
fi
done
done

This is an excellent hack.

Appreciate your post.

> Appreciate your post.

No probs, copyleft (c) 🙂

Actually I’ve seen yours:

$ for z in *.zip; do unzip $z; done

But, it was not enough for me, ’cause we have password protected ones… So, can say that idea comes from you 🙂 I just added a new feature (validation)…

I think it should/can be improved further to check for other exit status codes…

Maybe later some day…

I used to use for i in *.zip ; do unzip $i ; done as well but then I found out about the following command and use it all the time now.

escape the asterik and you are good to go. 🙂

I tried unzip -P $PASSWD $Z_FILE; command but it is not working and for same zip file it is working in US with same password. I read in one of the web sites that, non USA system needs to install a patch for running above command. If yes Please let me know where can I get this patch else please let me know how to run this command.

Thanks, just what I needed! Very straitghtforward. +1 virtual cookie for you.

If you have spaces in your filenames, you can also use the following:

for z in *.zip; do unzip “$z”; done

find -name \*.zip -exec unzip <> \;

find -name \*.zip | xargs -t -i unzip <>

If you like to extract multiple tar or tar.gz use the following command
for f in *.tar.gz; do tar zxf $f; done

Thanks all for sharing, very useful information about Unzip.

Question: and if I want do delete a file in a batch of different compressed archives? Lets say all copies of “info.txt” or “logo.jpg” in a.zip, b.zip, c.zip(…) z.zip, etc. There is a way to do it?

excellent post …. short method is really awesome..

Exactly what I was looking for! THANK YOU!

Time saver, life saver! Thank you!

thanks a lot …..4 help

if u want to display some msg then…

Thanks everyone for the answers. If space is an issue, you can do something like (from some dude) to remove the archive files as they are unpackaged:
for z in *.zip; do unzip $z; rm $z; done

I have 1..10 zip files in one directory …i want to unzip all files at a time..
can any one help how to do that

Thank you very much.

Thank you very much, on my Debian option #2 works very well!

I had a pile of zip that each contained a index.html file and the archive structure had no folder.. They obviously had to be extracted in separate folders so as to not overwrite the so precious files. Since it was a temporary “view and delete” kind of thing and with well over a hundred files (not needing to be unzipped in a specific folder, current folder was just fine), i came up with this;

for z in *.zip; do q=$(echo $z | cut -f 1 -d ‘.’); unzip $z -d ./$q; done;

It basically extracts all the zip files to the current directory, into a folder named after the zip filename. Greatly inspired (if not totally ripped from!) NixCraft and http://stackoverflow.com/questions/12152626/how-can-remove-the-extension-of-a-filename-in-a-shell-script

Couple seconds after i figured “oh well”, i saved that much time so i might as well make something out of it… So instead of just ‘hardcoding’ it into a simple bash alias that doesn’t take parameters, I took a couple more minutes to have it let me at least input a base directory for extraction. Here’s what i came up with (function in .bashrc file);

unzipALL() <
dir=’.’;
[[ ! -z «$<1>» ]] && dir=$1;
for z in *.zip; do
q=$(echo $z | cut -f 1 -d ‘.’);
unzip $z -d $dir/$q;
done;
>

From the command line just use unzipAll to unzip to the current folder or pass it a folder name: unzipAll /tmp extracts all to /tmp/%filename%.

It does perform a single basic check on the passed parameter but nothing too fancy (strip spaces before/after then checks against null). One could spend more time and cutomize it further, adding bad directory check and all that…

I figure i’d share… thanks and hopefuly it can be of use to someone!

I hope i didn’t break any rules posting a url in here, sorry if so heeh

Awesome job and thanks for sharing it with us.

unzip “*.zip” should also be OK.

unzip *.zip does not work in bash.

blah@blahblah:

/tmp-zip$ unzip *.zip
Archive: test1.zip
caution: filename not matched: test2.zip
blah@blahblah:

unzip \*.zip DOES work, still doesn’t solve the problem i faced of multiple same-name files…

blah@blahblah:

/tmp-zip$ unzip \*.zip
[. ]
inflating: index.html
inflating: portfolio.html
inflating: services.html
Archive: test2.zip
replace index.html? [y]es, [n]o, [A]ll, [N]one, [r]ename:

unzip “*.zip” results in the same, btw.

Hence the quick function. If you have a better way please share
Also, while testing you assumptions, i found out that unzip tries to look for .ZIP files on it’s own – pretty neat… unzip \* would work (still not help with the issue…)

I just pulled a lot of files (over 400K) all of them were in zip, i’m trying to make huge archive off free documents at http://uploadcoins.com , so for me worked # unzip \*.zip , all that 400K went ok 🙂 , so again, You can use unzip \*.zip , Good luck

I want a script to extract a particular file from the multiple zip folder.

Источник

Читайте также:  Windows с новым панель задач
Оцените статью