- Установка и использование 7-Zip в Linux
- Формат 7-Zip
- Установка 7-Zip в Linux
- Установка 7-Zip в Ubuntu, Debian
- Установка 7-Zip в Fedora, CentOS
- Установка 7-Zip в ArchLinux
- Раcпаковка 7zip-архивов
- Распаковать в текущую директорию
- Распаковать в определенную директорию
- Распаковать без сохранения структуры директорий
- Создание 7zip-архива
- Упаковать один файл
- Упаковать несколько файлов
- Упаковать директорию и ее содержимое
- Добавить файлы в существующий архив
- Просмотр файлов в архиве
- Протестировать целостность архива
- Заключение
- 7z «ultra» settings for zip format
- 1 Answer 1
- x=[0 | 1 | 3 | 5 | 7 | 9 ]
- mem=[b|k|m]
- mt=[off | on | ]
- Get Maximum Compression from 7zip compression algorithm
- 4 Answers 4
- How to use 7z to compress via pipe?
- 6 Answers 6
- Multithreaded support in 7za
- 5 Answers 5
Установка и использование 7-Zip в Linux
Формат 7-Zip
Формат 7-Zip впервые появился в 1999 году. Данный формат отличает высокая степень сжатия данных. По сравнению с ZIP степень сжатия 7-Zip может быть на 30-50% лучше. 7-Zip в основном используется среди пользователей Windows.
7-Zip нельзя использовать для создания резервных копий в Linux, так как формат не сохраняет информацию о правах доступа к файлам и данные о владельце.
В данной заметке мы рассмотрим, как установить поддержку 7-Zip в некоторых дистрибутивах Linux, а также как работать с 7zip-архивами.
Установка 7-Zip в Linux
Установка 7-Zip в Ubuntu, Debian
Для установки поддержки 7-Zip в Ubuntu и Debian, а также производных от них дистрибутивах (LinuxMint и др.), доступно три пакета:
- p7zip — базовая версия, которая поддерживает только архивы в формате .7z Представляет собой порт утилиты 7za.exe для POSIX систем.
- p7zip-full — полная версия, которая поддерживает различные алгоритмы сжатия при создании 7zip-архивов, а также другие форматы архивов. Установка данного пакета также обеспечивает поддержку 7-Zip в менеджере архивов File Roller, который используется в Ubuntu.
- p7zip-rar — отдельный модуль для p7zip, позволяющий распаковывать RAR-архивы.
Для установки 7-Zip в Ubuntu (Debian) вы можете установить пакет p7zip-full, а также p7zip-rar для поддержки RAR. Для этого выполните в терминале команду:
Примечание: В новых версиях Ubuntu (например, в Ubuntu 18.04 и новее) 7-Zip автоматический поддерживается в файловом менеджере Nautilus. Можно создавать и распаковывать 7zip архивы.
Установка 7-Zip в Fedora, CentOS
В дистрибутивах Fedora, CentOS доступны пакеты p7zip, p7zip-plugins.
Для установки используйте следующую команду:
Установка 7-Zip в ArchLinux
Для установки поддержки 7-Zip в ArchLinux установите пакет p7zip, который доступен в официальных репозиториях дистрибутива.
Раcпаковка 7zip-архивов
Когда поддержка 7-Zip установлена, то для распаковки .7z файлов вы можете использовать графические утилиты (например, File Roller, Ark), средства файлового менеджера вашего дистрибутива (если есть поддержка), а также командую строку.
Для работы с 7-Zip архивами через командную строку используется команда 7z
Распаковать в текущую директорию
Чтобы распаковать .7z архив в текущую директорию с сохранением структуры директорий, которые находятся внутри архива, выполните в терминале команду:
Файлы архива будут распакованы в текущую директорию. Если в архиве содержатся директории, то при распаковке их структура будет сохранена.
Распаковать в определенную директорию
Чтобы распаковать архив в определенную директорию используется опция -o , за которой без пробела указывается путь до директории.
Распаковать без сохранения структуры директорий
Можно распаковать .7z архив, не сохраняя структуру директорий. То есть, если внутри архива есть директории и файлы в них, то при распаковке все файлы будут распакованы в одну директорию. Для этого используется опция (команда) e .
Создание 7zip-архива
Упаковать один файл
Чтобы создать .7z архив используется следующая команда.
В результате выполнения данной команды будет создан архив archive.7z , который содержит файл myfile.txt
Упаковать несколько файлов
Чтобы упаковать несколько файлов, перечислите их имена через пробел.
Упаковать директорию и ее содержимое
Вместо файла, при создании архива, можно указать путь до директории, которую необходимо сжать.
Добавить файлы в существующий архив
Если архив уже создан, то можно добавлять в него новые файлы. Для этого используется такая же команда, как и для создания архива, только в качестве названия архива указывается существующий файл.
Просмотр файлов в архиве
Для просмотра содержимого архива используется команда:
Протестировать целостность архива
Чтобы проверить целостность архива (проверить, что архив «не битый») используется команда:
Заключение
Мы рассмотрели как установить поддержку 7-Zip в популярных дистрибутивах Linux, а также рассмотрели базовые возможности работы с 7zip-архивами.
Утилита 7z имеет много возможностей. Чтобы получить дополнительную информацию можно использовать следующие команды:
Источник
7z «ultra» settings for zip format
7z «ultra» settings for .7z format are:
What are the «ultra» settings for .zip format (using 7z)?
1 Answer 1
The defaults for the GUI application file-roller can also be changed:
Be aware that «ultra» may not be very efficient and will just take longer to compress while producing no significant difference in resulting file size than the default settings and may also introduce incompatibilities with other programs.
According to: file:///usr/share/doc/p7zip-full/DOCS/MANUAL/switches/method.htm
This is a link to your filesystem, just put it in the address bar of your webbrowser.
If you are currently not on a computer where the package is installed you could download the DEB package and browse it with another archiver. If my memory serves me correctly, almost the same file should be included in the Windows installer.
By default (if cl and cu switches are not specified), 7-Zip uses UTF-8 encoding only for file names that contain symbols unsupported by local code page.
x=[0 | 1 | 3 | 5 | 7 | 9 ]
Sets level of compression. x=0 means Copy mode (no compression).
Deflate / Deflate64 settings:
x=1 and x=3 with Deflate method set fast mode for compression.
Sets the number of fast bytes for the Deflate/Deflate64 encoder. It can be in the range from 3 to 258 (257 for Deflate64). Usually, a big number gives a little bit better compression ratio and a slower compression process. A large fast bytes parameter can significantly increase the compression ratio for files which contain long identical sequences of bytes.
Sets number of passes for Deflate encoder. It can be in the range from 1 to 15 for Deflate and from 1 to 10 for BZip2. Usually, a big number gives a little bit better compression ratio and a slower compression process.
Sets the Dictionary size for BZip2. You must specify the size in bytes, kilobytes, or megabytes. The maximum value for the Dictionary size is 900000b. If you do not specify any symbol from set [b|k|m], dictionary size will be calculated as DictionarySize = 2^Size bytes.
mem=[b|k|m]
Sets the size of memory used for PPMd. You must specify the size in bytes, kilobytes, or megabytes. The maximum value is 256 MB = 2^28 bytes. The default value is 24 (16MB). If you do not specify any symbol from the set [b|k|m], the memory size will be calculated as (2^Size) bytes. PPMd uses the same amount of memory for compression and decompression.
Sets the model order for PPMd. The size must be in the range [2,16]. The default value is 8.
mt=[off | on | ]
Sets multithread mode. If you have a multiprocessor or multicore system, you can get a speed increase with this switch. This option affects only compression (with any method) and decompression of BZip2 streams. Each thread in the multithread mode uses 32 MB of RAM for buffering. If you specify
Источник
Get Maximum Compression from 7zip compression algorithm
I am trying to compress some of my large document files. But most of files are getting compresses by only 10% maximum. I am using 7zip Terminal Commands.
7z a filename.7z -m0=LZMA -mx=9 -mmt=on -aoa -mfb=64 filename.pptx
Any suggestion on changing parameters. I need at least 30% compression ratio.
4 Answers 4
.pptx files or .docx files are internally .zip archives. You can not expect a lot of compression on an already compressed file.
Documentation states lzma2 handles better data that can not be compressed, so you can try with
But the required 30% is almost unreachable.
If you really need that compression, you could use the fact that a pptx is just a fancy zip file:
Unzip the pptx, then compress it with 7zip. To recover an equivalent (but not identical) pptx decompress with 7zip and recompress with zip.
There are probably some complications, for example with epub there is a certain file that must be stored uncompressed as first file in the archive at a certain offset from the start. I’m not familiar with pptx, but it might have similar requirements.
I think it’s unlikely that the small reduction in file size is worth the trouble, but it’s the only approach I can think of.
Depending on what’s responsible for the size of the pptx you could also try to compress the contained files. For example by recompressing png files with a better compressor, stripping unnecessary data (e.g. meta-data or change histories) or applying lossy compression with lower quality settings for jpeg files.
Well just an idea to max compressing is
- ‘recompress’ these .zip archives(the .docx, .pptx, jar. ) using -m0 (storing = NoCompression) and then
- apply lzma2 on them
lzma2 is petty good — however if the file contains many jpg’s consider to give the opensource packer peazip or more specify paq8o a try. Paq8 has a build in Jpeg compressor and supports range compression. So it will also come along with jpg’s the are inside some other file. Winzip’s zipx in contrast to this will require pure jpg files and is useless in this case.
But again to make PAQ effectively working/compressing your target file you’ll need to ‘null’ the zip/deflate compression, turn it into an uncompressed zip.
Источник
How to use 7z to compress via pipe?
I’m using this for creating backups securely (? — is it really secure? with a good password?):
Q: But how can I do this using 7z with max compression rate?
Creating temporary files besides the only OUTPUT file is not good, because if I need to compress
100 GByte sized files/directories on a 180 GByte FS I wouldn’t have enough free space (if ex.: the compressed file would take
6 Answers 6
This is covered in the man page of 7z:
Is there a reason you want to use 7z specifically, or do you just want better compression than gzip ?
The xz utility uses the same compression algorithm as 7z (LZMA), and allows piped compression the same as gzip .
Some examples of reading from stdin and writing to stdout:
- a create archive. Requires a filename; we’re using just .xz to abuse it to set the archive type, since we don’t actually care about a name
- -si read from stdin
- -so write to stdout
- x extract; must also specify -t the type since we didn’t create an archive w/ filename
To quickly create an remote backup preparation file of all my home scripts.I use the following:
Reason I don’t backup my ‘home’ root is that I specifically sync and send only some directories. Notice how cpio will skip and check for newer existing files on restore. This is powerful. Your work will not be overwritten.
For the record as this thread is quite old.
7-zip does not allow streamed write of 7z format, it requires free seeking access as it writes, amongst the other stuff, header at the end of operation. It does allow to pipe standard *nix formats like bz2, gz, xz, though. It also allows to pipe single input without restrictions ( -si switch).
So one can compress single file into 7z format but cannot pipe it further.
Other formats, like mentioned bz2, gz, xz can be written to stdout ( -so switch).
This obviously allows to pipe it further:
Note -an switch that disables parsing of archive_name. What it actually does, god one knows — this program is bit magical and you have to cope with its quirks. Example of this behaviour can be found here.
Источник
Multithreaded support in 7za
(I posted this first on serverfault, but then I realized it probably belongs here.)
I’m trying compress a very large text file using 7za (p7zip) 9.20. The -mmt option doesn’t seem to have any effect. I’ve tried both -mmt=on and -mmt=2. This is an 8-core machine. One person suggested adding -m0=lzma2 as an argument, but that just gives me E_INVALIDARG. Does anybody know how to make this work?
This has no effect:
And this fails with an error:
5 Answers 5
According to -m (Set compression Method) switch # ZipMultiThread — 7ZIP manual & documentation, mt defaults to on , so there’s no need to specify it at all.
However, 7zip’s implementation of the DEFLATE algorithm doesn’t support multi-threading!
As you have already discovered,
only uses one core.
But .zip files compress every file individually. When compressing several files, the multi-threading option compresses one file per core at once.
Try it and you’ll see that
will use all available N cores.
If you want to speed up the compression of a single file, you have two choices:
Split up bigfile in chunks.
Use a different compression algorithm.
For example, 7zip’s implementation of the BZip2 algorithm supports multi-threading.
Also, the syntax error is caused by your attempt to use the LZM Algorithm for a .zip container. That’s not possible.
The possible algorithms for .zip conatiners are DEFLATE(64), BZip2 and no compression.
If you want to use the LZM Algorithm, use a .7z container. This container also handles the following algorithms: PPMd, BZip2, DEFLATE, BCJ, BCJ2 and no compression.
This is an old question, and not the answer to the specific question, but an answer to the spirit of the question (Using all cores to compress a zip format)
pigz (parallel gzip with .zip option)
This will give you a zip compatible file 7x faster for same compression level.
A quick comparisons of zip compatible and non-zip compressors using single and multiple cores.
wall times on i7-2600k to compress 1.0gb txt file on fedora 20
wall times to decompress
Another option, to achieve multi-theaded compression on Linux is to use what Facebook uses, Zstandard. On Ubuntu, you install it like this:
Super fast multi-threaded compression:
You can specify compression levels 1-19 (3 is default).
Max compression (slowest):
Medium compression (level 10):
My overall experience is that Zstandard compression isn’t as strong as 7zip, but it is way faster and the zstdmt command tries to use all cores.
BTW, on Window, 7zip uses all processors by default and I’m very disappointed that this is not the case in Linux. Its been this way for several years, at this point, and I wish 7zip was multi-threaded by default in Linux too.
Verified and tested: To use multithreading on 7za the parameter must be «-mmt#» not «-mmt=#», putting the equal sign makes it to ignore.
How i had discovered? After i run 7z without any parameter it shows the info about parameters, on switches it say «-mmt[N]», not «-mmt=[N]»
So if i understand well, the parameter you are typing «-mmt=2» may be misswritten and may be «-mmt2», without the equal sign.
Not sure if i understand well, my english is really poor.
By the way, why you use «7za» instead of just «7z»?
So to test the parameter i run a set of commands to do benchkmarks and that confirmed the typo error on some documentation. The correct parameter must be typed without the equal sign.
Command to do a benchmark with 7z with only one thread: 7z b -mmt1
Command to do a benchmark with 7z with only two threads: 7z b -mmt2
Command to do a benchmark with 7za with only two threads: 7za b -mmt2
Command to do a benchmark with 7za with only one thread: 7za b -mmt1
There is no equal sign on the parameter ˋ-mmt#ˋ, neither for 7z, nor 7za.
Источник