How to unzip zip archive in linux

Содержание
  1. Как распаковать Zip-архив в Linux
  2. How to Unzip Files in Linux
  3. В этом руководстве мы объясним, как разархивировать файлы в системах Linux через командную строку с помощью unzip команды.
  4. Установка unzip
  5. Установить unzip на Ubuntu и Debian
  6. Установить unzip на CentOS и Fedora
  7. Как распаковать ZIP файл
  8. Подавить вывод unzip команды
  9. Распакуйте ZIP-файл в другой каталог
  10. Распакуйте ZIP-файл, защищенный паролем
  11. Исключить файлы при распаковке ZIP-файла
  12. Перезаписать существующие файлы
  13. Распакуйте ZIP-файл без перезаписи существующих файлов
  14. Распакуйте несколько ZIP-файлов
  15. Перечислите содержимое файла Zip
  16. Вывод
  17. How to Zip and UnZip Files in Linux
  18. Zip file (Compress)
  19. Unzip file (Extract)
  20. More Zip and Unzip Command Options
  21. 1) Compressing the current directory
  22. 2) Compressing all the file in current directory
  23. 3) Extracting all the compressed file in the current directory
  24. 4) Forcefully overwrite existing files when decompressing
  25. 5) Compressing file to another directory
  26. 6) Decompressing archive to another directory
  27. 7) Best compression
  28. 8) Compressing multiple files
  29. 9) See the content of a zip file without decompressing
  30. 10) Extracting one or more file from a compressed archive
  31. 11) Exclude certain file during the decompression
  32. 12) Decompressing an archive without creating directories
  33. 13) List detailed information about the archive
  34. 14) Update one file or more files of the compressed archive
  35. 15) Update all the files of the compressed archive
  36. 16) Do compression and extraction quietly
  37. 17) Converting text files when decompressing
  38. 18) Compressing only sub-directory of a main directory into individual archive
  39. 19) Compressing both files and directory into individual archive
  40. 20) Show detailed information about a compressed archive
  41. Conclusion
  42. How to Unzip a Zip File in Linux [Beginner’s Tutorial]
  43. Unzip file in Linux command line
  44. Unzip to directory
  45. See the content of zip file without unzipping it
  46. Unzip files in Linux using GUI

Как распаковать Zip-архив в Linux

How to Unzip Files in Linux

В этом руководстве мы объясним, как разархивировать файлы в системах Linux через командную строку с помощью unzip команды.

ZIP является наиболее широко используемым форматом архивных файлов, который поддерживает сжатие данных без потерь. ZIP-файл — это контейнер данных, содержащий один или несколько сжатых файлов или каталогов.

Установка unzip

unzip не устанавливается по умолчанию в большинстве дистрибутивов Linux, но вы можете легко установить его, используя менеджер пакетов вашего дистрибутива.

Установить unzip на Ubuntu и Debian

Установить unzip на CentOS и Fedora

Как распаковать ZIP файл

В простейшем случае unzip команда без каких-либо параметров извлекает все файлы из указанного ZIP-архива в текущий каталог.

В качестве примера, скажем, вы загрузили установочный ZIP-файл WordPress . Чтобы разархивировать этот файл в текущий каталог, вам нужно просто выполнить следующую команду:

ZIP-файлы не поддерживают информацию о владельце в стиле Linux. Извлеченные файлы принадлежат пользователю, который запускает команду.

У вас должны быть права на запись в каталог, в который вы распаковываете ZIP-архив.

Подавить вывод unzip команды

По умолчанию unzip печатает имена всех извлекаемых файлов и сводные данные, когда извлечение завершено.

Используйте -q переключатель, чтобы подавить печать этих сообщений.

Распакуйте ZIP-файл в другой каталог

Чтобы разархивировать ZIP-файл в каталог, отличный от текущего, используйте -d переключатель:

Например, чтобы разархивировать архив WordPress latest.zip в /var/www/ каталог, вы должны использовать следующую команду:

В приведенной выше команде мы используем, sudo потому что обычно пользователь, в который мы вошли, не имеет разрешения на запись в /var/www каталог. Когда файлы ZIP распаковываются с использованием sudo , извлеченные файлы и каталоги принадлежат пользователю root.

Распакуйте ZIP-файл, защищенный паролем

Чтобы разархивировать файл, защищенный паролем, вызовите unzip команду с -P параметром, за которым следует пароль:

Ввод пароля в командной строке небезопасен и его следует избегать. Более безопасным вариантом является обычное извлечение файла без указания пароля. Если файл ZIP зашифрован, unzip вам будет предложено ввести пароль:

unzip будет использовать один и тот же пароль для всех зашифрованных файлов, если он правильный.

Исключить файлы при распаковке ZIP-файла

Чтобы исключить извлечение определенных файлов или каталогов, используйте -x параметр, за которым следует разделенный пробелами список архивных файлов, которые вы хотите исключить из извлечения:

В следующем примере мы извлекаем все файлы и каталоги из архива ZIP, кроме .git каталога:

Перезаписать существующие файлы

Допустим, вы уже распаковали ZIP-файл и снова запускаете ту же команду:

По умолчанию unzip вас спросят, хотите ли вы перезаписать только текущий файл, перезаписать все файлы, пропустить извлечение текущего файла, пропустить извлечение всех файлов или переименовать текущий файл.

Если вы хотите перезаписать существующие файлы без запроса, используйте -o параметр:

Используйте эту опцию с осторожностью. Если вы внесли какие-либо изменения в файлы, изменения будут потеряны.

Распакуйте ZIP-файл без перезаписи существующих файлов

Допустим, вы уже распаковали ZIP-файл и внесли изменения в некоторые файлы, но случайно удалили несколько файлов. Вы хотите сохранить изменения и восстановить удаленные файлы из архива ZIP.

Читайте также:  Linux cpu performance mode

В этом случае используйте -n параметр, который заставляет unzip пропустить извлечение файла, который уже существует:

Распакуйте несколько ZIP-файлов

Вы можете использовать регулярные выражения для сопоставления нескольких архивов.

Например, если у вас есть несколько ZIP-файлов в вашем текущем рабочем каталоге, вы можете разархивировать все файлы, используя только одну команду:

Обратите внимание на одинарные кавычки *.zip . Если вы забыли процитировать аргумент, оболочка расширит символ подстановки, и вы получите ошибку.

Перечислите содержимое файла Zip

Чтобы просмотреть содержимое файла ZIP, используйте -l параметр:

В приведенном ниже примере мы перечисляем все установочные файлы WordPress:

Вывод будет выглядеть так:

Вывод

unzip это утилита, которая помогает вам составлять список, тестировать и извлекать сжатые ZIP-архивы.

Чтобы создать ZIP-архив в системе Linux, вам нужно использовать команду zip .

В этом руководстве мы объясним, как разархивировать файлы в системах Linux через командную строку с помощью unzip команды.

Источник

How to Zip and UnZip Files in Linux

Compression utilities compress files (borg and rar) and are similar in their functions and operations. Zip/unzip is one of the commands used in Linux to create compressed files and to extract. In modern Linux distros these utilities are installed by default. If any issues, you can install both these utilities from the shell prompt but you must be a root user to do so.

On RedHat/CentOS based system

On Ubuntu/Debian based system

  • Zip is a compression and file packaging utility for Linux and Unix.
  • Unzip will list, test, or extract files from ZIP archive files.

The zip and unzip programs work exactly in the same way as PKZIP and PKUNZIP in the DOS environment. Compressed files use less disk space than normal files and they transfer faster than larger uncompressed files. In Linux, you can compress files with the help of Gzip or Zip. If you exchange files with non-Linux users then you can use zip to avoid compatibility problems.

Zip file (Compress)

The compression process replaces the original file with a new file that has an additional extension which is .zip (the case of zip command), so don’t delete the .zip files that you create. They are the original files in a compressed wrapper! The syntax is in the form

  • option: there are available options of zip command
  • -b path: where to save temporally the zip file until the compression finish and then copy it in the current working directory
  • filezip: it is the name of zip file which will be created
  • file: it is the name of the original file. It can be more than one file

The command given below creates a file file.zip which contains a copy of the file named file10 located in the current directory.

To compress a folder, we used -r option of zip command. The command given below will compress the directory script-test into the file name back.zip:

See how it operates on the file’s directory too. You can see the result

You can add the .zip extension at the end of the zip file yourself.

The command will directly understand without adding the same extension again.

You can see the result.

Unzip file (Extract)

Unzip command extract the .zip file only. So we will use it to extract the zip files created. To extract a file do as below

It extracts the content in the current directory. So, if there are the originals files, it will ask if you want to replace it

When the zip file contains more than one file, it will do the operation with all the files. Let’s try to extract the zip folder

More Zip and Unzip Command Options

1) Compressing the current directory

The command given below will compress the current directory and also all sub-directories:

2) Compressing all the file in current directory

The command written below will create a file called backfile.zip which contains all files in the current directory. File names that start with a «.» are not included.

3) Extracting all the compressed file in the current directory

You can extract all the zip file as below

4) Forcefully overwrite existing files when decompressing

During the decompression, if there are originals files, unzip command will ask you if you want to replace or to rename the newly extracted files. The operation can be not easy if you have some files in the compressed archive.

So you can force the unzip command to overwrite the existing files with unzip -o command

5) Compressing file to another directory

It is possible to zip a file and save the zip file in another directory by indicating the new destination path with the name of the zip file at the end.

Читайте также:  Sony vaio vgn установка windows с флешки

6) Decompressing archive to another directory

As with the compression operation, it is possible to extract files into another directory. It is with -d option of unzip command

7) Best compression

You can also try -9 option for best compression as shown below:

8) Compressing multiple files

It is possible to compress multiples files into one zip file. And we compress it to another directory

9) See the content of a zip file without decompressing

It is possible to see the content of a zip file with the unzip -l command. It is like when you list a detail the content of a folder without move on it.

10) Extracting one or more file from a compressed archive

If a compressed archive has more than one file, it is possible to extract only one or more files. This operation will not extract all the file of the compressed archive. You need to specify each filename to extract

Using the command above means that you already know exactly the name of the files to extract. So, it means for example that you have listed the content of the compressed archive with unzip -l command

11) Exclude certain file during the decompression

As we are able to filter file to extract, it is possible to exclude certain files during the decompression

You can check if a compressed archive has not error. It is possible with unzip -t command

12) Decompressing an archive without creating directories

If a compressed archive contains a folder, during the extraction operation it will recreate the exact structure. It is possible to extract the archive without creating the folder which were already presents. But their contents will be extracted directly

We will consider the zip archive of the example above. It contains folder1 and script-test folders, we will extract without creating the two

You can see the folders are not present

13) List detailed information about the archive

It is possible to have the detail information about the content of an archive like with ls -l command.

It will give some information such as the archive name, its total size, and the total number of files in it. The trailer gives the number of files listed, the total uncompressed and compressed data size of the listed files (not counting internal zipfile headers), and the compression ratio.

14) Update one file or more files of the compressed archive

Suppose we have compressed an archive then, modified a file. There is a possibility to add the update file to the compressed archive with the zip -u command.

In the example below, we have updated a file toto and add a new file papi

You can the date on the output of each command. You can see that the update date is may instead of april

15) Update all the files of the compressed archive

You can replace (freshen) an existing entry in the zip archive only if it has been modified more recently than the version already in the zip archive. Unlike the update option, this will not add files that are not already in the zip archive.

16) Do compression and extraction quietly

When we do compression of extraction, normally zip command show the output of the operation. It is possible to decide not to show the result to the output with -q option of zip command but we will need to check the result after a certain time

17) Converting text files when decompressing

Some non-linux systems store text files with two end-of-line characters CR and LF rather than the more efficient single character (LF) used on all Unix systems. You can have issue compatibility. You can use unzip -a to face it with a mnemonic for ASCII conversion. It converts files that are supposedly text, while leaving alone those that are marked binary.

18) Compressing only sub-directory of a main directory into individual archive

Suppose that we have a folder with some files and sub-directories. Now suppose that we only need to compressed theses sub-directory. I will give you a script line to do it. Make sure you enter to the main directory first.

We will first check if we are into the correct directory

Now let’s see the sub-directories we have

You can see that we have pap and pop sub-folder. Let’s try our script

Let’s check their zip files

You can see that it creates the zip folder with the respectively name. Note that our command only compress each level 1 sub-directory of the main directory not every descendant directory of the sub-directory.

Читайте также:  Windows best games download

If you want to see how this works, include an echo before the zip and you will see the commands printed instead of executed.

19) Compressing both files and directory into individual archive

You can compress both the files and directories into individual archive for some reason. To do it, you can use the script line below

20) Show detailed information about a compressed archive

You can have more detail information about a compressed archive with -v option of unzip command

Conclusion

In this tutorial, we have understood the compression(zip) and decompression(unzip) concept and we have seen how we can manipulate compressed files. Let us know if you know about more options.

Источник

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:

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.

Источник

Оцените статью