- Примеры использования zip и unzip в linux
- Установка zip и unzip:
- Пример использования утилиты zip
- Zipping and Unzipping Files under Linux
- ziping files/directories examples
- unziping files/directories examples
- Linux GUI packages
- ZIP command in Linux with examples
- Как распаковать ZIP в Linux
- Распаковка ZIP Linux
- Как распаковать ZIP Linux с помощью 7z
- Выводы
Примеры использования 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: Извлечь конкретный файл из архива
Источник
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 command in Linux with examples
ZIP is a compression and file packaging utility for Unix. Each file is stored in single .zip <.zip-filename>file with the extension .zip.
- zip is used to compress the files to reduce file size and also used as file package utility. zip is available in many operating systems like unix, linux, windows etc.
- If you have a limited bandwidth between two servers and want to transfer the files faster, then zip the files and transfer.
- The zip program puts one or more compressed files into a single zip archive, along with information about the files (name, path, date, time of last modification, protection, and check information to verify file integrity). An entire directory structure can be packed into a zip archive with a single command.
- Compression ratios of 2:1 to 3:1 are common for text files. zip has one compression method (deflation) and can also store files without compression. zip automatically chooses the better of the two for each file to be compressed.
The program is useful for packaging a set of files for distribution; for archiving files; and for saving disk space by temporarily compressing unused files or directories.
Syntax for Creating a zip file:
Extracting files from zip file
Unzip will list, test, or extract files from a ZIP archive, commonly found on Unix systems. The default behavior (with no options) is to extract into the current directory (and sub-directories below it) all files from the specified ZIP archive.
Options :
1. -d Option: Removes the file from the zip archive. After creating a zip file, you can remove a file from the archive using the -d option.
Suppose we have following files in my current directory are listed below:
hello1.c
hello2.c
hello3.c
hello4.c
hello5.c
hello6.c
hello7.c
hello8.c
Syntax :
After removing hello7.c from myfile.zip file, the files can be restored with unzip command
2.-u Option: Updates the file in the zip archive. This option can be used to update the specified list of files or add new files to the existing zip file. Update an existing entry in the zip archive only if it has been modified more recently than the version already in the zip archive.
Syntax:
Suppose we have following files in my current directory are listed below:
hello1.c
hello2.c
hello3.c
hello4.c
After updating hello5.c from myfile.zip file, the files can be restored with unzip command
3. -m Option: Deletes the original files after zipping. Move the specified files into the zip archive actually, this deletes the target directories/files after making the specified zip archive. If a directory becomes empty after removal of the files, the directory is also removed. No deletions are done until zip has created the archive without error. This is useful for conserving disk space, but is potentially dangerous removing all input files.
Syntax :
Suppose we have following files in my current directory are listed below:
hello1.c
hello2.c
hello3.c
hello4.c
After this command has been executed by the terminal here is the result:
4.-r Option: To zip a directory recursively, use the -r option with the zip command and it will recursively zips the files in a directory. This option helps you to zip all the files present in the specified directory.
Syntax:
Suppose we have following files in my current directory (docs) are listed below:
unix.pdf
oracle.pdf
linux.pdf
5. -x Option: Exclude the files in creating the zip. Let say you are zipping all the files in the current directory and want to exclude some unwanted files. You can exclude these unwanted files using the -x option.
Syntax :
Suppose we have following files in my current directory are listed below:
hello1.c
hello2.c
hello3.c
hello4.c
This command on execution will compress all the files except hello3.c
6.-v Option: Verbose mode or print diagnostic version info. Normally, when applied to real operations, this option enables the display of a progress indicator during compression and requests verbose diagnostic info about zip file structure oddities.
When -v is the only command line argument, and either stdin or stdout is not redirected to a file, a diagnostic screen is printed. In addition to the help screen header with program name, version, and release date, some pointers to the Info-ZIP home and distribution sites are given. Then, it shows information about the target environment (compiler type and version, OS version, compilation date and the enabled optional features used to create the zip executable.
Syntax :
Suppose we have following files in my current directory are listed below:
hello1.c
hello2.c
hello3.c
hello4.c
This article is contributed by Mohak Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Источник
Как распаковать ZIP в Linux
В операционной системе Windows формат архивов ZIP считается чуть ли не стандартным, он даже поддерживается в этой операционной системе, что называется «из коробки». Если вы только перешли с Windows, то у вас, наверное, есть много таких архивов с различными файлами, также ZIP-архивы могут часто попадаться на просторах интернета. Поэтому работать с такими файлами в Linux вам однозначно придётся.
В этой небольшой статье мы рассмотрим, как распаковать ZIP Linux. Разберём несколько способов и воспользуемся несколькими утилитами, которые справятся с этой задачей.
Распаковка ZIP Linux
Формат ZIP был создан в 1989 году на замену очень медленному формату ARC. Здесь используется сжатие deflate, и на то время оно работало намного быстрее чем ARC. Исторически сложилось так, что стандартным форматом для Linux стали TAR и GZ — это усовершенствованные алгоритмы сжатия и архивации. Многие графические распаковки воспринимают и ZIP-файлы. Но они обрабатывают архивы не сами, а дают команду предназначенным для этого формата утилитам.
Утилита для распаковки ZIP называется unzip, она не всегда установлена по умолчанию. Но вы можете очень просто добавить её в свою систему из официальных репозиториев. Для этого в Ubuntu выполните:
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. Мы рассмотрели два способа ,и теперь вы точно будете знать, что делать, когда столкнетесь с такой ситуацией. Если у вас остались вопросы, спрашивайте в комментариях!
Источник