Unzipping in linux terminal

2 Easiest Ways to Unzip Files in Linux?

Unzipping is a process to restore the compressed file without any data loss. In Linux distributions, the unzip utility is utilized to serve the purpose. In Linux, the terminal and the GUI (where applicable) of Linux can also be utilized to unzip files. Considering its importance, this guide will demonstrate various methods to unzip files in Linux(Linux-based OS). The content that illustrates this guideline is mentioned below:

  • Prerequisite: How to Install unzip Package in Linux?
  • How Does the unzip Command Work?
  • How to Unzip files in Linux Using GUI?
  • Bonus Tip: How to Zip Files in Linux?

Prerequisite: How to Install unzip Package in Linux?

The Linux terminal assists the audience in installing the needed packages from the package manager. To install the unzip package on Debian-based distros, execute the below script:

Now, the unzip package has been successfully installed in Ubuntu (Linux-based OS). To install it on your desired Linux distribution, choose one of the commands written below:

For CentOS:

For Fedora/Redhat:

For Arch:

For OpenSUSE

$ sudo zypper install unzip

How Does the unzip Command Work?

The unzip command works simply to extract the archived file and place all content that is present in the zip file paste in the same directory. The general syntax that follows to unzip the archive file is as follows:

Syntax:

Using the “help” utility of unzip command, all possible options with descriptions are as follows:

How to Use unzip Command in Linux?

In Linux, the “unzip” command extracts all files from the zip archive and pastes them into the same directory. The step-by-step procedure is explained here to access and unzip the specified file:

Example 1: Unzip a File in the Same Directory

An existing zip file, “office.zip”, is carried out after navigating to the specific directory “office”. To display all files and directories in this directory, execute the “ls” command as below:

Execute unzip Command

Execute the “unzip” command specifying the name of the zip file as “office.zip”. It extracts all compressed directories and files which is stored in the zip file:

Users can display a message after successfully executing the above command.

Verify Unzipped Files in the Same Directory

In the office directory, you can verify through the “ls” command that two files, “office1.txt” and “office2.txt”, have been extracted here:

Читайте также:  Kali linux комбинации клавиш

Example 2: Unzip a File in Different Directory

Another example is considered using the “-d” option that store to the extracted files in the specified directory as below:

$ unzip Office.zip -d myfolder

The output shows that “a.out”, “file.sh”, “office” files have been successfully in the “myfolder” directory.

Example 3: Unzip Specific Files From Zip File

To unzip a specific file, the “-x” utility is used to extract the specific file and paste it into the same directory. To do so, the syntax is given below:

You can verify that “file.sh” has been extracted in the Home directory utilizing the “ls” command as below:

Example 4: Unzip an Encrypted File

Another example is adapted to encrypt the zip file to display all the content that is stored in multiple files. For this, the “-p” utility is used here:

The output confirms that all content is displayed in the above terminal.

Example 5: Unzip Multiple Files

Users can unzip multiple files by specifying the file type. To unzip different files type, the command is provided below:

$ unzip Office.zip file.sh a.out

The output shows that specified files have been unzipped here.

How to Unzip files in Linux Using GUI?

In Linux, GUI (where applicable) assists in achieving the same task in less time. To unzip files using the GUI in Linux, the step-by-step procedure is provided below:

Example 1: Unzip a File in the Same Directory

An “office.zip” file is considered to perform the unzipping operation. To do so, press the right button of the mouse on the zip file and choose the “Extract here” option from the dropdown list:

After hitting the “Extract Here” option, the “office1.txt” and “office2.txt” have been extracted in the same directory as seen below:

Example 2: Unzip Files to a Specific Directory

You have the option to choose the specific directory to unzip the archive file. For this, select the “Extract to” option by hitting the right button of the mouse on the specified zip file:

It navigates to the new window for selecting the destination. In our case, choose the “CEO” directory and hit the “Select” button located at the top right corner of the window:

Now, users can verify that unzipped files “office1.txt” and “office2.txt” are saved in the “CEO” directory:

Bonus Tip: How to Zip Files in Linux?

A piece of additional information to make a zip file. To do so, there are three existing files in the “Office” directory as seen below through the “ls” command:

Читайте также:  Linux mp4 to wmv

Two files, “file.sh” and “office”, are considered to make a zip file whose name will be “Boss.zip”. For this, execute the command:

$ zip Boss.zip file.sh office

The “ls” command is utilized to display the zip file “Boss.zip” successfully created here:

That’s all from this guide.

Conclusion

In Linux- based OS, the “unzip” command is utilized to unzip files that need to be installed before using it. The “unzip” command requires the name of the zip file for extraction by following the general syntax “unzip filename.zip”. Additionally, a GUI method has also been explained to unzip files into the same as well as specific directories through the “Extract Here” and “Extract to” options, respectively. This guide has provided a brief explanation to unzip files in Linux.

Источник

Как распаковать ZIP в Linux

В операционной системе Windows формат архивов ZIP считается чуть ли не стандартным, он даже поддерживается в этой операционной системе, что называется «из коробки». Если вы только перешли с Windows, то у вас, наверное, есть много таких архивов с различными файлами, также ZIP-архивы могут часто попадаться на просторах интернета. Поэтому работать с такими файлами в Linux вам однозначно придётся.

В этой небольшой статье мы рассмотрим, как распаковать ZIP Linux. Разберём несколько способов и воспользуемся несколькими утилитами, которые справятся с этой задачей.

Распаковка ZIP Linux

Формат ZIP был создан в 1989 году на замену очень медленному формату ARC. Здесь используется сжатие deflate, и на то время оно работало намного быстрее чем ARC. Исторически сложилось так, что стандартным форматом для Linux стали TAR и GZ — это усовершенствованные алгоритмы сжатия и архивации. Многие графические распаковки воспринимают и ZIP-файлы. Но они обрабатывают архивы не сами, а дают команду предназначенным для этого формата утилитам.

Утилита для распаковки ZIP называется unzip, она не всегда установлена по умолчанию. Но вы можете очень просто добавить её в свою систему из официальных репозиториев. Для этого в Ubuntu выполните:

А в системах, использующих формат пакетов Red Hat, команда будет выглядеть немного по-другому:

sudo yum install unzip zip

После установки большинство графических утилит для работы с архивами смогут распаковать архив ZIP Linux. Команда ZIP Linux установлена на случай, если вы захотите создавать ZIP-архивы.

Но этой утилите не нужны дополнительные оболочки для распаковки архива. Вы можете сделать всё прямо из консоли. Давайте рассмотрим синтаксис утилиты:

$ unzip опции файл_архива.zip файлы -x исключить -d папка

  • файл архива — это тот файл, с которым нам предстоит работать;
  • файлы — здесь вы можете указать файлы, которые нужно извлечь, разделять имена файлов пробелом;
  • исключить — файлы, которые извлекать не нужно;
  • папка — папка, в которую будет распакован архив.

Теперь рассмотрим опции утилиты, поскольку она позволяет не только распаковывать архивы, но и выполнять с ними определённые действия:

  • -l — вывести список файлов в архиве;
  • -t — протестировать файл архива на ошибки;
  • -u — обновить существующие файлы на диске;
  • -z — вывести комментарий к архиву;
  • -c — извлекать файлы на стандартный вывод, перед каждым файлом будет выводиться его имя;
  • -p — то же самое, только имя выводится не будет;
  • -f — извлечь только те файлы, которые уже существуют на диске, и файлы в архиве более новые;
  • -v — вывести всю доступную информацию;
  • -P — указать пароль для расшифровки архива;
  • -n — не перезаписывать существующие файлы;
  • -j — игнорировать структуру архива и распаковать всё в текущую папку;
  • -q — выводить минимум информации.
Читайте также:  Linux administration with python

Все самые основные опции рассмотрели, теперь давайте рассмотрим несколько примеров работы с программой в терминале. Чтобы распаковать ZIP Linux в текущую папку, достаточно набрать:

zip3

Причём расширение указывать не обязательно. Протестировать архив можно с помощью опции -t:

zip1

Вы можете протестировать все архивы в текущей папке, выполнив:

Если нужно распаковывать архив не в текущую папку, можно очень просто указать нужную:

zip4

Также можно распаковывать не весь архив, а только нужные файлы или файлы нужного формата:

unzip имя_файла.zip \*.txt -d /tmp

С помощью опции -l вы можете посмотреть список файлов в архиве:

zip

Утилиту unzip разобрали и теперь вы с ней точно справитесь. Но я говорил, что мы рассмотрим несколько способов, как выполняется распаковка ZIP Linux. Поэтому дальше мы поговорим об утилите 7z.

Демонстрация работы утилит zip и unzip в терминале:

Как распаковать ZIP Linux с помощью 7z

7z — это кроссплатформенный набор утилит для работы с архивами. Кроме собственного формата, здесь поддерживается большое количество других, в том числе tar и zip. Плюс этой утилиты — в контекстное меню файлового менеджера будет добавлен пункт, с помощью которого вы сможете распаковывать или создавать архивы.

Для установки утилиты в Ubuntu или Debian выполните:

sudo apt install p7zip-full

Теперь вы можете использовать контекстное меню вашего файлового менеджера, чтобы распаковать архив ZIP Linux. Также можно использовать программу в консоли. Синтаксис очень похож на unzip:

$ 7z команда опции имя_архива

Команда задаёт нужное действие. Нас будут интересовать только четыре команды:

Теперь рассмотрим самые полезные опции:

  • -o — указать папку для распаковки;
  • -p — указать пароль;
  • -x — не извлекать эти файлы;
  • -w — указать рабочую директорию;
  • -y — отвечать положительно на все вопросы;

Ну и рассмотрим примеры работы с утилитой. Сначала проверим содержимое архива:

zip5

Распаковываем архив, сохраняя структуру подкаталогов:

zip6

Или распаковываем все файлы в одну папку, игнорируя подкаталоги:

Или вы можете указать папку, в которую нужно распаковать файлы с помощью опции -o:

Выводы

В этой статье была рассмотрена распаковка ZIP Linux, как видите, это ненамного сложнее, чем распаковка стандартных архивов TAR. Мы рассмотрели два способа ,и теперь вы точно будете знать, что делать, когда столкнетесь с такой ситуацией. Если у вас остались вопросы, спрашивайте в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

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