Unzipping windows files on linux

Zipping and Unzipping Files under Linux

Asked by Yamir via e-mail

Question: MS-Windows has winzip program. I cannot find anything under Application menu to zip or unzip files on Linux. I am using Debian Linux. How do I zip and unzip file under Linux operating systems?

Answer: Linux has both zip and unzip program. By default, these utilities are not installed. You can install zip/unzip tools from the shell prompt. Open the Terminal by clicking on Application > System Tools > Terminal. You must be a root user, Type the following two commands to install zip and unzip program on Debian or Ubuntu Linux:

OR
$ sudo apt-get install zip unzip
If you are Red Hat Linux/Fedora/CentOS Linux user then you can use the yum command to install zip and unzip program as follows:

  • zip is a compression and file packaging utility for Linux and Unix (including FreeBSD, Solaris etc).
  • unzip will list, test, or extract files from a ZIP archive files.

ziping files/directories examples

Creates the archive data.zip and puts all the files in the current directory in it in compressed form, type:

Note: No need to add .zip extension or suffix as it is added automatically by zip command.
Use the ls command to verify new zip file:
$ ls
To zip up an entire directory (including all subdirectories), type the following command:

unziping files/directories examples

To use unzip to extract all files of the archive pics.zip into the current directory & subdirectories:

You can also test pics.zip, printing only a summary message indicating whether the archive is OK or not:

To extract the file called cv.doc from pics.zip:

To extract all files into the /tmp directory:

  • 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

To list all files from pics.zip:

Linux GUI packages

You can use the following graphics packages

(1) KDE Desktop: Ark is an Archive Manager for the KDE Desktop. You can start Ark from Application > Accessories.

(2)GNOME Desktop: File Roller ia an Archive Manager for the GNOME Desktop.

See also

For more information please consult the following resources:

  • Compressing files under Linux or UNIX cheat sheet
  • Read man pages of zip and unzip (type man zip or man unzip at shell prompt)
  • ark handbook
  • File Roller home page

Источник

How to Use Unzip in Linux

Zipping and unzipping files eases a lot of complicated tasks like file transfer! In this tutorial, you’ll learn how to use unzip in Linux to improve your VPS workflow!

Zip is a commonly used compression function which is portable and easy to use. You can even unzip files in Windows, that were created in Linux!

Unzip is a utility that is not available on most Linux flavors by default, but can be easily installed. By creating .zip files you can match .tar.gz file compression!

Читайте также:  Не подключается удаленный рабочий стол windows 10 домашняя

Below are a few scenarios in which you may choose to use zip files:

When you are frequently working between Windows and Unix based systems. Not only does this compress files but also is a file package utility. Works on multiple operating systems

To save bandwidth. If you have limited or restricted bandwidth, then zip can be used between two servers for file transfer

Transfers files quickly. Zip utility reduces file size, therefore reducing transfer time

Upload or download directories at a faster speed

Save disk space

Unzip password protected .zip files

Enjoy a good compression ratio

Remember, before taking advantage of Unzip on Linux, you’ll have to SSH into your VPS server.

Debian and Ubuntu Systems

Installing unzip is easy! With Ubuntu and Debian use the command below to install unzip:

Sit back and wait a minute, until the installation is finished.

To create zip files, you’ll also have to install zip. You can do this with the following command:

Install Unzip on Linux CentOS and Fedora

This again is simple and can be done using below command:

Once the installation is complete you can check the path with the following command:

After you execute the direction in the command line, you should get an output that looks like this:

You can also confirm everything is installed properly by using the command bellow. It will give a verbose with unzip utility details.

How to Use Zip and Unzip in Linux

Now that we know how to install the utility, we can start learning the basic uses of it:

Create Zip Files in Linux

The basic syntax to create a .zip file is:

To test this, we created two files – ExampleFile.txt and ExampleFile1.txt. We’ll compress them into sampleZipFile.zip with the following command:

Using Linux to Unzip a file

The unzip command can be used without any options. This will unzip all files to the current directory. One such example is as shown below:

This by default will be unzipped in the current folder provided you have read-write access.

Remove a File from a .zip File

Once a .zip file is created, you can remove or delete files in it. So, if you want to remove ExampleFile.txt from the existing sampleZipFile.zip, then you can use the following command:

Once this command is executed, you can unzip the .zip file using:

Over here you will find that ExampleFile.txt has been removed and can’t be seen on extraction.

How to Update Zip Files

Once a .zip file is created, you can add a new file to an existing .zip file. Suppose a new file ExampleFile2.txt needs to be added to the already existing sampleZipFile.zip. You can do this with the command shown below:

Now if you extract sampleZipFile.zip, you will find the new file ExampleFile2.txt added to it.

Move a File to a Zip

You can easily move specific files to an the zip file. That means that after adding the files, they will be deleted from their original directories. This is mostly used when you have large file or directory, but need to conserve disk space. This is done by adding the -m option. A sample of this command would be:

Recursive Use of Zip on Linux

The -r option is used to recursively zip files. This option will compress all the files present within a folder. An example of such command is as shown below:

In the example, MyDirectory is a directory which has multiple files and sub-directories to be zipped.

Exclude Files in a Zip

While creating a .zip file, you can exclude unwanted files. This is done by using the -x option. Below is an example:

Here ExampleFile.txt will not be added to the sampleZipFile.zip.

Unzip to a Different Directory

In case you do not want to unzip to the current directory but want to specify a directory location, then this can also be done. Use the -d option to provide a directory path in the unzip command. An example of such command is as shown below:

Читайте также:  Операционная система microsoft windows 10 домашняя box

Use Linux Unzip with Multiple Zip Files

If you want to unzip multiple zip files existing within your current working directory then you can use a command as shown below:

This command will unzip all the individual zip files.

Suppress Output When Using Unzip in Linux

By default, when we use the unzip command, the command prints list of all the files that are getting extracted. A summary of the extraction process is printed. In case you want to suppress these messages, then you can use the -q option. The command would be as shown below:

Exclude Files Using Unzip in Linux

In case you want to extract all files except for one, then you can use a similar command as shown below:

Here the command will unzip all files except excludedFile.txt.

You can also prevent specific file types from getting extracted. One such example is as shown below:

The above command will exclude all .png files from being extracted.

Using Unzip in Linux with Password Protected Files

A password protected .zip file can be decompressed using the -P option. A sample of such command is as shown below:

In the above command, Password will be the password for the .zip file.

Overriding Zip Files

When you unzip the same file again in the same location where the file was extracted, by default you will encounter a message asking whether you want to overwrite the current file, overwrite all files, skip extraction for the current file, skip extraction for all files or rename current file.

The options would be as shown below:

You can override these files by using the -o options. One such example is as shown below:

Caution should be taken while executing this command since this will completely overwrite the existing copies. Any changes made in the earlier copy will be overwritten.

Using Linux Unzip Without Overwriting Files

If you have unzipped a file and made some changes but you accidentally deleted a few files, then you can use this approach to restore it! Use the -n option to skip the extraction in case a file already exists. So effectively only files which do not exist will be extracted. An example of such a command is:

How to List the Content of a Zip in Linux

The -l option will list all the files within the .zip along with the timestamp and other basic details. An example of such command is:

Wrapping Up

That’s it, you’re introduced to all the essential functions of the zip and unzip Linux utilities. Start improving your file management right now!

Edward is an expert communicator with years of experience in IT as a writer, marketer, and Linux enthusiast. IT is a core pillar of his life, personal and professional. Edward’s goal is to encourage millions to achieve an impactful online presence. He also really loves dogs, guitars, and everything related to space.

Источник

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

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

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

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

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

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

Читайте также:  Утилита для linux для форматирования флешек

sudo apt install unzip

А в системах, использующих формат пакетов 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 — выводить минимум информации.

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

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

unzip -tq имя_файла.zip

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

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

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

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

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

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

unzip -l file.zip

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

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

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

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

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

sudo apt install p7zip-full

А в Red Hat и CentOS:

sudo yum install p7zip

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

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

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

  • e (Extract) — извлечь файлы из архива;
  • x eXtract — извлечь файлы из архива, сохраняя полный путь;
  • l (List) — список файлов архива;
  • t (Test) — проверить архив.

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

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

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

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

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

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

7z x файл.zip -o /tmp/

Выводы

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

Источник

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