Opening zip files linux

Примеры использования 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 To Unzip Files On Linux

So you’ve been sent a .zip file as an attachment and now you’re stuck figuring how to extract it’s content? Or some such! Luckily you’ve stumbled upon the right place, as at ezyZip we eat zip files for breakfast! Linux offers various solutions to uncompressing zip files, depending on your configuration and variant.

Below we outline some common methods to unzipping files on the Linux environment.

Quick Tip!

Looking to quickly open zip archive without hassle? Use ezyZip! 😊
It runs in the browser, so no need to install any extra software. Just navigate to the unzip page and follow the given instructions. It’s FREE!

Using the GUI to unzip files on Linux

The simplest approach is to use the GUI. Below we show the steps involved when using the default desktop environment that comes with each linux distribution. If you are using a custom setup, then these steps might not apply. Use the command line unzip options if you are stuck!

Extract zip file with Ubuntu / Debian

  1. Open the Files app and navigate to the directory where zip file is located.
  2. Locate the file which you want to unzip.
  3. Right click on the file and the context menu will appear with list of options.
  4. Select “Extract Here” option to unzip files into the present working directory or choose “Extract to. ” for a different directory.
Читайте также:  Не запускаются приложения windows 10 что делать

Extract zip file with Mint

  1. Steps are same as above. Just note that an «Extract to. » option is not provided with the default installation.

That’s it, you have successfully unzipped the file. Optionally you could also use the Gnome Archive Mananger, which offers more advanced options and support for other file types.

Other Linux unzip applications

There is a myriad of dedicated archive management applications that can be utilised for unzipping files. Some are packaged with the distribution and others can be installed separately.

Extract zip file with Archive Manager

Archive Manager comes as a default installation with many Linux distros and is quick & easy way to decompress archives.

  1. Open the Files app and navigate to the directory where zip file is located.
  2. Right click the file and select «Open With Archive Manager».
  3. Archive Manager will open and display the contents of the zip file. Click «Extract» on the menu bar to uncompress the contents into the current directory.

Extract zip file with Ark

Ark is another archive manager that ships as a default in a lot of distributions.

  1. Open Ark. It will initially say «No archive loaded»
  2. Select «Open. » from the top Archive menu
  3. It will open the contents of the zip file into Ark. Select «Extract All > Extract To» from the Archive menu
    Extract To»>
  4. Select the directory you wish to extract the files to and then click «Extract»

How to unzip on Linux using terminal

If you want to work like a pro and desire more powerful features, you have to move towards command line interface. Fire up your terminal and run one of the following commands to complete your desired task. The examples assume you have a filename called backup.zip.

Install unzip on Linux

If unzip command is not installed on your system, then you’ll need to do that first.
sudo apt install unzip

Unzip on the Linux command line

The simplest option that will extract the contents to current directory:
unzip backup.zip

To change the target directory for extracted material, use -d option followed by the desired directory:
unzip backup.zip -d ./restore-directory

To preview contents of zip file:
unzip -l backup.zip

If you don’t want to unzip the whole file, then add the specific files to extract at the end:
unzip backup.zip file1 subdirectory/file2

The inverse of the above command. Unzip every file EXCEPT the ones specified after the -x modifier:
unzip backup.zip -x file1 subdirectory/file2

Unzipping a password protected file:
unzip -p mypassword backup.zip

Unzip files on command line with unarchiver

A great free set of unarchiving command line utilities are supplied by the Unarchiver. There is a GUI too but that is currently only offered to MacOS users.

The best part about these utilities is that they support dozens of other file formats (e.g. rar, 7z, arj etc. ) and the command line syntax is the same for all of them.

Install unarchiver

Unarchive files

To uncompress a file:
unar backup.zip

Uncompress file to a different directory:
unar -o ./output-directory backup.zip

Check out all the other parameters available with:
unar -h

Unzip tar.gz files on command line

Linux and other unix variants commonly use tar and gz to package collection of files into a single package (e.g. software packages). To use the GUI for opening tar.gz files, follow the zip file instructions above. The command line options however are slightly different:

First uncompress the gz file:
gunzip filename.tar.gz

The output of the above should be filename.tar. Now to extract the tar file contents:
tar xvf filename.tar

You can combine the above two commands by adding a «z» option:
tar zxvf filename.tar.gz

Alternately, you could use ezyZip to extract tar.gz files or open tar file individually.

Unzip 7z files on command line

Another compression format that you will often encounter is 7z.

Читайте также:  Media feature pack windows 10 pro n что это

Install p7zip (if needed)
sudo apt-get install p7zip-full

To extract a 7z archive:
7z e backup.7z

Unzip zipx files on command line

The zipx file format is commonly associated with WinZip and not available for linux users. However fear not, you can use the 7zip utility to open zipx files in linux!

Install p7zip (if needed)
sudo apt-get install p7zip-full

Источник

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

Источник

Работа с ZIP архивом в Linux

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

Программа zip — это звезда в мире ПО (ну не считая rar) этот формат очень популярен для windows систем и он по умолчанию уже встроен в незапятнанную сборку операционной системы, поэтому только установив виндовус вы уже можете разархивировать файлы в формате zip. Когда вы установите unzip, все утилиты для работы с архивами смогут без проблем распаковать архив zip.

Читайте также:  Запуск командной строки без windows

Установка программы Zip в Linux

Рассмотрим на примере Debian или Ubuntu

apt-get install zip unzip

Чтобы создать ваш первоначальный архив в формате zip используйте команду zip — первый аргумент это название архива, второй это файл или компданные через пробел, которые будут добавлены в архив:

zip archive.zip file1.txt file2.log

Как добавить в картотека zip папку с файлами:

zip archive.zip -r /var/log/

Установить пароль на архив можно с помощью ключа -P, а ключ -e утаит пароль при вводе :

zip archive.zip -re /var/log/

Для распаковки архивов Zip используйте команду unzip, можно использовать её без каких-нибудь опций, распаковка в таком случае будет произведена в текущую директорию:

Применяйте ключ -d для указания директории, куда нужно распаковать архив:

unzip archive.zip -d /tmp

Посмотреть компданные в архиве без распаковки можно с ключом -l :

unzip archive.zip -l

Как распаковать определённые файлы из архива? Зачислите их через пробел:

unzip archive.zip 1.txt 2.txt

Пример создания архива. Заархивируем все файлы и папки в папки /var/log/ и директорию /var/spool/:

zip -r -9 test-archive.zip /var/log/* /var/spool/* -x «/var/log/apt/*»
-r — архивировать рекурсивно
-9 — степень сжатия от 1 до 9. 0 — без стягивания.
test-archive.zip — имя архива
/var/log/* /var/spool/* — архивируемые директории через пробел
-x «/var/log/apt/*» — опция, дозволяющая исключить указанную папку или файл из архива
-e — опция, позволяющая задать пароль на архив

Творение ZIP архива в Linux

Для начала запомним шаблон или синтаксис команды для создания архива zip в linux:

zip [функции] [файлы или папки которые будем упаковывать]

Опции для создания архива tar:

r (recurse) — общерекурсивное создание архива
s (size) — разбивка архива на определенный размер k (kB), m (MB), g (GB) или t (TB)
пример: zip -s 300m
на выводе получим:
file.zip (300 mb, master file)
file.001.zip (300 mb)
file.002.zip (300 mb)
file.003.zip (100 mb)
P (password) — запаролировать картотека (можно использовать ключ e тогда пароль будете вводить в отдельной строке со звездочками )
образчик: zip -P мойпароль -r file.zip ./home/nibbl/foto
пример2: zip -er file.zip ./home/nibbl/foto
x — ликвидируем файлы или каталоги из архива
1-9 — степень сжатия (где 1 без сжатия, а 9 лучшее сжатие)
zip –r -9 -P 123 — archive.zip /home/nibbl/desktop/myfile

— этой командой мы заархивировали с сжатием папку myfile создали архив с именем archive.zip и установили пароль на картотека 123

Распаковать zip архив в Linux

Далее мы затронем две свободных популярных утилиты, управление которыми исполняется через консоль, то есть пользователю придется вводить встроенные и дополнительные команды для управления абсолютно всеми файлами и инструментами. Примером сегодня выступит дистрибутив Ubuntu, а для обладателей других сборок мы делаем акценты на каких-либо несовпадениях. Рассмотрим синтаксис команды что бы распаковать или разархивировать tar архив:

Функции для создания архива tar:

d (directory) — указать директорию для разархивации
l — вывести список файлов в картотеке
d — удалить определенный файл или каталог из уже сделанного архива
v — показывает детальную информацию по файлам в картотеке ()

unzip — распаковываем архив в категорию в которой находимся
unzip -d /home/nibbl/desktop — распаковываем картотека на рабочий стол

Общая информация по работе с Zip в Linux

zip —help или unzip —help — вызов ссылки по командам и параметрам
man zip или man unzip — вызов расширенной документации официальная документация по команде zip — ссылка

Просмотр охватываемого zip архива в Linux

Вы можете проверить содержимое zip-файла даже не извлекая его с помощью опции -l.

unzip -l zipped_file.zip

Вот, что выведет терминал после ввода:

unzip -l metallic-container.zip
Archive: metallic-container.zip
Length Date Time Name
——— ———- —— —-
6576010 2019-03-07 10:30 625993-PNZP34-678.jpg
1462 2019-03-07 13:39 License free.txt
1116 2019-03-07 13:39 License премиум.txt
——— ——-
6578588 3 files

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

Источник

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