7 zip командная строка windows 7

Обновлено Обновлено:
Опубликовано Опубликовано:

Что такое 7zip.

Приведенные ниже команды выполняются после перехода в каталог с установленным 7-Zip. Как правило, это:

cd «C:\Program Files\7-Zip»

Архивирование и разархивирование
    Как распаковать
    Как запаковать
Резервное копирование
    Пример cmd-скрипта
    Пример powershell-скрипта
Описание ключей и команд
    Команды
    Ключи
Примеры использования команд
    Исключение файлов и папок
    Архивирование базы 1С

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

Общий синтаксис:

7z <команда> <ключи> <пути к каталогам и файлам>

Синтаксис для распаковки:

7z <x или e> <архивный файл> -o»<путь, куда распаковываем>»

* ключ x распаковывает с сохранением каталожной структуры; e — все в одно место.

Пример:

7z x c:\temp\archive.7z -o»c:\temp\»

* в данном примере мы распакуем файл c:\temp\archive.7z в папку c:\temp

Архивация

Синтаксис для архивирования:

7z a <ключи> <архивный файл> <объект архивирования>

Например:

7z a -tzip -mx5 -r0 c:\temp\archive.zip c:\temp

* в данном примере мы создадим zip-архив с уровнем компрессии 5; в архив попадет все содержимое всех каталогов; название для файла c:\temp\archive.zip; запаковываем все содержимое папки c:\temp.

7z a -mx1 c:\temp\archive.7z c:\temp\file1.txt c:\temp\file2.txt c:\temp\file3.txt

* в данном примере мы архивируем файлы c:\temp\file1.txt, c:\temp\file2.txt, c:\temp\file3.txt с низкой компрессией 1; в итоге будет получен архив c:\temp\archive.7z.

* описание ключей ниже.

Резервное копирование с помощью 7-Zip

Один из самых распространенных примеров использования 7zip из командной строки — резервирование данных.

Для начала переходим в каталог с установленной программой:

cd «C:\Program Files\7-Zip\»

* так как в пути имеется пробел, его необходимо писать в кавычках.

Сама команда выглядит следующим образом:

7z a -tzip -ssw -mx1 -pPassword -r0 C:\Temp\backup.zip C:\Data

* в данном примере мы архивируем содержимое папки C:\Data и сохраняем в виде файла C:\Temp\backup.zip.
* описание ключей смотрите ниже или командой 7z —help.

Полный пример cmd-скрипта для резервного копирования:

@echo off

set source=»C:\Date»
set destination=»C:\Temp»
set passwd=»Password»
set dd=%DATE:~0,2%
set mm=%DATE:~3,2%
set yyyy=%DATE:~6,4%
set curdate=%dd%-%mm%-%yyyy%

«C:\Program Files\7-Zip\7z.exe» a -tzip -ssw -mx1 -p%passwd% -r0 %destination%\backup_%curdate%.zip %source%

* данный скрипт заархивирует содержимое каталога C:\Data в файл C:\Temp\backup_<текущая дата>.zip. Полученный архив будет защищен паролем Password.
* содержимое необходимо сохранить в файле с расширением .cmd или .bat.

Пример Powershell скрипта для резервного копирования:

$source = «C:\Date»
$destination = «C:\Temp»
$passwd = «Password»
$curdate = (Get-Date -UFormat «%d-%m-%Y»)

& «C:\Program Files\7-Zip\7z.exe» a -tzip -ssw -mx1 -p$passwd -r0 $destination\backup_$curdate.zip $source

* данный скрипт также заархивирует содержимое каталога C:\Data в файл C:\Temp\backup_<текущая дата>.zip. Полученный архив будет защищен паролем Password.
* содержимое необходимо сохранить в файле с расширением .ps1.

Описание ключей и команд 7z

В синтаксисе работы с 7zip идут команды и ключи.

Описание основных команд

Команда Описание
a Добавление файлов в архив. Если архивного файла не существует, создает его.
d Удаление файла из архива
e Извлечение файлов из архива. Все файлы оказываются в одной папке.
l Вывод содержимого архива.
rn Переименовывание файла внутри архива.
u Обновление файлов в архиве. Если файла нет, создает новый.
x Извлечение файлов из архива. Пути сохраняются.

Описание ключей

Часто используемые:

Ключ Описание
-t Тип архива. По умолчанию создаются файлы в формате 7z. Примеры, -tzip, -tgz
-ssw Включить файл в архив, даже если он в данный момент используется. Для резервного копирования очень полезный ключ.
-mx Уровень компрессии. 0 — без компрессии (быстро), 9 — самая большая компрессия (медленно). Например, -mx4
-p Пароль для архива. Например, -pStrong2!3paSsword
-o Задает директорию, например, в которую будут распакованы файлы.
-r Рекурсивное архивирование для папок. Задается числом от 0 (все каталоги) до количества уровней каталогов, которые нужно включить в архив.

Другие полезные ключи:

Ключ Описание
-sdel Удалить файлы после создания архива.
-sfx Создание самораспаковывающегося sfx-архива.
-y Утвердительно ответить на все вопросы, которые может запросить система.
-x Исключить файлы или папки из архива.
-v Позволяет разбить архив на фрагменты. Если указать -v1g, то архив будет разбит на части по 1 Гб.
-mmt Количество потоков процессора, которые можно задействовать для работы программы. -mmt=4 укажет работать в четыре потока.
-m Задает метод сжатия. Доступны варианты:
— LZMA: базовый метод для сжатия 7z. Быстрое сжатие и декомпрессия.
— LZMA2: метод по умолчанию для 7z. Поддерживает несколько процессорных потоков.
— PPMd: метод PPMdH Дмитрия Шкарина с небольшими изменениями. Хорошо подходит для текстовых файлов.
— BZip2: на основе алгоритма BWT. Также хорош для текстовых файлов.
— Deflate: стандартный метод для форматов ZIP и GZip. Сжатие не очень хорошее, но высокая скорость работы. Поддерживает только 32 КБ словаря.
— Deflate64: аналогичен Deflate, но с поддержкой 64 КБ словаря.

Полный список ключей и команд можно получить командой 7z —help.

Примеры

Исключение файлов и папок

Отдельно стоит рассказать про возможность исключения. Есть два варианта ее применения.

Первый — создать список исключений в отдельном файле.

Пример команды 7z:

7z.exe a -tzip -ssw -mx9 -r0 -x@exclus.txt C:\Temp\backup.zip C:\Data

* где exclus.txt — файл с исключениями.

Пример файла с исключениями:

test
*.tmp

* в данном примере мы исключаем каталог с именем test и все файлы с расширением tmp.

Второй — указать исключение в команде.

7z.exe a -tzip -ssw -mx9 -r0 -xr!Шаблон* C:\Temp\backup.zip C:\Data

Резервирование баз 1С

 Данные базы 1С находятся в файлах с расширением .1CD. Для их резервирования используем команду:

7z.exe a -tzip -mmt=2 -ssw -mx5 -r0 C:\Temp\backup.zip D:\Bases_1C\*.1CD

* в данном примере мы будем сжимать все файлы 1CD в архив C:\Temp\backup.zip.

This tutorial shows 7-Zip on the command line. Compress, extract, archive and optimize with the 7za.exe executable.

7-Zip is an effective compression program.

The 7za.exe program is used to compress, extract and update files through the command line. It provides superior compression. It is open-source. This makes it easy to obtain and use.

Start. First you need to download the 7-Zip command line executable, 7za.exe. This is the exe you will use to run commands on archives. Please go to 7-zip.org and get the command line version.

Tip: For convenience and so you don’t need to change environment paths, put the 7za.exe file in your user directory.

Next: Open the Windows console and test the 7za.exe program out with a few commands. Type in the exe name 7za and this will display.

7-Zip default output

7-Zip (A)  4.60 beta  Copyright (c) 1999-2008 Igor Pavlov
    2008-08-19

Usage: 7za <command> [<switches>...] <archive_name>
       [<file_names>...]
       [<@listfiles...>]

We see the grammar we need to use with 7za.exe. The «command» is the main verb. Then you specify optional switches, the archive name (either source or destination archives) and files. My user directory is «C:\Users\Sam\».

Command a. You can use the «a» command with the single letter a. This command stands for «archive» or «add.» Use it to put files in an archive. You have to specify the destination archive, and the source files (in that order).

On the test system, the directory C:\Users\Sam contains two files (file1.txt and file2.txt). The command puts those two files in an archive, and you need to type it into the command prompt.

C:\Users\Sam>7za a -t7z files.7z *.txt

7-Zip (A)  4.60 beta  Copyright (c) 1999-2008 Igor Pavlov  2008-08-19
Scanning

Creating archive files.7z

Compressing  file1.txt
Compressing  file2.txt

Everything is Ok

C:\Users\Sam>

Tip: To open your archive, right click on it and select 7-Zip -> Open archive. The screenshot shows the files compressed in files.7z.

Command d. Here we see an example of the «d» command in 7-Zip command lines. This stands for ‘delete’ and is used much less often. It allows you to remove a certain file (or set of files) from inside an archive.

Note: You will need this if you use huge archives and need to save time. This is from the manual.

7z d archive.zip *.bak -r

7z:          use executable
d:           delete files
archive.zip: delete from this archive
*.bak:       only match bak files
-r:          traverse all subdirectories

Tip: You can also remove a single file from an archive with «d». This is more useful when you do not have a solid archive.

Command e. Here we use the «e» command in your console window. The «e» stands for extract, and it means to unzip or expand an archive. You must specify the source archive always, and may also specify a destination.

Info: The «e» command extracts everything to a specified directory. Another command «x» can preserve directory structures in archives.

7z e archive.zip

7z:          executable
e:           use extract command
archive.zip: source archive you want to expand

Overwrite prompts: 7-Zip will always prompt you if there is a file it needs to overwrite to extract the new file.

However: This can be problematic if you are scripting or embedding 7za.exe. In that case, see the -y switch.

Command l. We next use the single-letter «l» (lowercase letter ell) command. The lowercase L is used to list the contents of archives and you probably will not need to use it often. I thought I would test it and show an example.

Next: This shows the listing of a solid archive. The originals are 27216 bytes and 3888 bytes. They compress down to 1030 bytes.

C:\Users\Sam>7za l files.7z

7-Zip (A)  4.60 beta  Copyright (c) 1999-2008 Igor Pavlov  2008-08-19

Listing archive: files.7z

Method = LZMA
Solid = +
Blocks = 1
Physical Size = 1202
Headers Size = 172

   Date      Time    Attr         Size   Compressed  Name
------------------- ----- ------------ ------------  ------------------------
2008-10-02 15:48:01 ....A        27216         1030  file1.txt
2008-10-02 15:47:45 ....A         3888               file2.txt
------------------- ----- ------------ ------------  ------------------------
				 31104         1030  2 files, 0 folders

Command t. Here we use the «t» command in the 7z program. This command allows you to test the integrity of archives. It stands for ‘test’ and is much less useful than the «-t» switch. Don’t confuse the two. This one is used for diagnostics.

7z t archive.zip *.doc -r

7z:          use this executable
t:           test the specified archive
archive.zip: the archive you want to test
*.doc:       test all these files in the archive
-r:          recurse all child directories

Command u. The «u» command in 7-Zip stands for update. This is a useful command and is great when you want to replace old files in your archive with newer files. This prevents needing to decompress and recompress the entire archive.

7z u archive.zip *.doc

7z:          executable name
u:           update command
archive.zip: archive you want to update files in
*.doc:       only update these files (Word documents)

Warning: The «u» command doesn’t work with solid archives. A solid archive is one where all the files are compressed together.

So: You cannot update specific files in solid archives with the «u» command. Solid archives are limited.

Switch m. We can change the optimization settings in 7-Zip on the command line. This is the most important and useful option you can use. It specifies the method of compression. Here I will show a bunch of options, and also some examples.

Compression Levels

Compression levels

Switch -mx0: Don't compress at all.
	     This is called "copy mode."

Switch -mx1: Low compression.
	     This is called "fastest" mode.

Switch -mx3: Fast compression mode.
	     Will automatically set various parameters.

Switch -mx5: Same as above, but "normal."

Switch -mx7: This means "maximum" compression.

Switch -mx9: This means "ultra" compression.
	     You probably want to use this.

Switch m, advanced. Here are advanced compression method (-m) switches. The first three are usually of limited use, but you might benefit from tweaking them. My experience is that manual optimizations to these options doesn’t produce big benefits.

Switch -mfb: Specifies number of fast bytes. Sometimes helps with «sparse» files. Don’t bother.

Switch -mpass: Number of passes for deflate compression. Don’t bother with this. Automatically set with levels.

Switch -md: This specifies dictionary size. It is automatically set, so don’t bother.

Switch -mmt: Enable multithreading. Use if you have quad-core and a huge archive. Specify «on» or «off». This may be enabled by default.

Command x. This command is like «e» except it preserves the full paths. If you have an elaborate or important directory structure, use this option. This would be most useful for system backups or really big backups. Here’s the example syntax.

7z x archive.zip

7z:          executable name
x:           use the extract command
archive.zip: the archive you want to extract all the files from

Switch t type. Here I show how to specify the precise archive type you want to create. Note that you can specify any filename you want for any type. But some extensions are recommended—they are standard.

Type switches

	  Switch: -t7z
	  Format: 7Z
Example filename: archive.7z (default option)

	  Switch: -tgzip
	  Format: GZIP
Example filename: archive.gzip, archive.gz

	  Switch: -tzip
	  Format: ZIP
Example filename: archive.zip (compatible)

	  Switch: -tbzip2
	  Format: BZIP2
Example filename: archive.bzip2

	  Switch: -ttar
	  Format: TAR
Example filename: tarball.tar (UNIX and Linux)

	  Switch: -tiso
	  Format: ISO
Example filename: image.iso (may not be supported)

	  Switch: -tudf
	  Format: UDF
Example filename: disk.udf

Also, the 7-Zip manual provides some useful examples for type switches. It shows the -tiso and -tudf switches. These are not the most common. Almost all of the examples in this document use -t switches.

7z a -tiso archive.iso
7z a -tudf archive.udf

7z:                         executable name
a:                          add to archive
-tiso or -tudf:             format of archive to create
archive.iso or archive.udf: name of archive to create

Solid archives. 7z is the only file format in 7-Zip that you can specify whether the archive is solid or not. Solid means all the files are compressed as one. It makes it impossible to use the «u» command to update individual files.

Switch -ms=on: Enable solid mode. This is the default so you won’t often need to specify it.

Switch -ms=off: Disable solid mode. Useful when you need to update individual files. Will reduce compression ratios normally.

7z archives. You can change many values and switches on 7z archives, with endless permutations. Some things you can change are dictionary sizes, FastBytes values, MatchFinder values, and filters. Normally you don’t need to deal with these.

PPMd. With the 7z format, you can specify the algorithm. PPMd is fast and effective for compressing plain text files. It is ideal for large collections of Word documents. PPMd does not perform as well on files containing binary data.

PPMd switch -mmem=24b, -mmem=24k, -mmem=24m: These control the amount of memory you use. They are useful and higher is normally better.

PPMd switch -mo=2, -mo=32: These specify the model order in PPMd. They are not normally useful.

When should I use PPMd? You should use PPMd when you have a large corpus (body) of text. This could include HTML or other formatting, but plain text should dominate. It can improve ratios by around 30% on some datasets.

Example commands. Here I show the example compression commands from the 7-Zip manual. I demonstrated simple ones at the start of this document. These are more complex. We use more features of the 7-Zip command line.

7z a -tzip archive.zip *.jpg -mx0

7z:          name of executable
a:           add to archive command
-tzip:       specify a ZIP archive (useful for compatibility)
archive.zip: destination archive
*.jpg:       only add jpg files to archive
-mx0:        don't compress, just copy
	     useful for already-compressed files

Example of 7z format. This next command line shows how to create a solid 7z archive of program files (executables). It uses multithreading mode, which means it will be fast on a dual core machine.

7z a -t7z archive.7z *.exe *.dll -ms -mmt

7z:         name of executable
a:          archive command specified
-t7z:       use 7z file type (less compatible and smaller results)
archive.7z: destination archive file
*.exe:      include all *.exe files in directory in new archive
*.dll:      include all *.dll files in new archive
-ms:        create solid archive (default)
-mmt:       multithread the operation (faster)

Create PPMd archive. PPMd is an extraordinary algorithm for compressing text and is relatively new. Here I show a command in the 7-Zip manual that compresses all the text files in the working directory. It creates a PPMd archive.

Tip: The command is useful because you will normally want to only compress text files with PPMd.

PPMd Compression

7z a -t7z archive.7z *.txt -m0=PPMd

7z:         executable name/path
a:          add command specified
-t7z:       use the 7z format (needed for PPMd)
archive.7z: destination archive file
*.txt:      select all text files
-mo=PPMd:   compress with this algorithm

Switch o. We show the «o» switch on the 7-Zip command line. Sometimes you do not want to extract to the current directory. This is where -o can come in handy. Use this to set the destination directory.

7z x archive.zip -oC:\Doc

7z:          executable name
x:           extract archive with paths intact
archive.zip: archive to extract files from
-oC:\Doc:    extract all files to the Doc folder on the C: drive

Switch p. We can use the «-p» switch, which refers to the word «password». This is really helpful when security and encryption is involved. You can specify a password on the command line. The syntax is a bit funky.

7za a pw.7z *.txt -pSECRET

7za:      name and path of 7-Zip executable
a:        add to archive
pw.7z:    name of destination archive
*.txt:    add all text files to destination archive
-pSECRET: specify the password "SECRET"

Opening password-protected archives. This next console output shows what happens when you try to open the password-protected archive. The password here is SECRET, which will allow the archive to be extracted.

C:\Users\Sam>7za x pw.7z

7-Zip (A)  4.60 beta  Copyright (c) 1999-2008 Igor Pavlov  2008-08-19

Processing archive: pw.7z

Enter password:

Header encryption: Add -mhe to encrypt headers. The password command will automatically deal with encrypted headers.

Tip: Remember, encrypted headers will hide the names of the files in your archive.

More switches. Here we take a closer look at more switches that are of limited use. They are useful to know, however, if you ever need to use them. Usually you can do better just by using the defaults that are slightly adjusted for your requirement.

Switch -ssc: Specify case-sensitive mode. The default is -ssc- on Windows (insensitive). The default is -scc on Linux (sensitive).

Switch -ssw: Compress locked files. You can try this if you have problems opening files.

Switch -w: Set working directory. You can use this when you want to specify temp folders.

Case-sensitive. We can use case-insensitive file names in the 7-Zip command line. For those of you who use both Linux and Windows, the case-sensitive option is useful. I will show my own example here with some explanation.

7za.exe a archive.7z Z*.* -ssc

7za.exe:    7-Zip command-line executable path and name
a:          archive command
archive.7z: add files to this target archive
Z*.*:       select only files whose first letter is a capital Z

Switch v. You can use the «v» switch on the command line. In data compression, a volume is a segment of a data set that is a certain number of bytes long. The volume switch specifies the exact size in bytes, kilobytes or megabytes.

Also: You can specify sequential volumes with the «v» switch on the 7za.exe command line.

Switch ao. The «ao» switch allows you to specify whether you want to overwrite old files. Be careful—you cannot restore an overwritten file normally. It takes another argument. Back up your data by copying the files in your file manager first.

Switch -aoa: This switch overwrites all destination files. Use it when the new versions are preferred.

Switch -aos: Skip over existing files without overwriting. Use this for files where the earliest version is most important.

Switch -aou: Avoid name collisions. New files extracted will have a number appending to their names. You will have to deal with them later.

Switch -aot: Rename existing files. This will not rename the new files, just the old ones already there.

Example of the switches

7z x test.zip -aoa

7z:       use the 7-zip executable
x:        use the extract command
test.zip: extract files from this archive
-aoa:     overwrite all existing files. risky!

Multiple files. This section addresses adding multiple files to an archive. To add many files to one archive, please use the «a» command and the wildcard * symbol. Specify the name of the destination archive file and the source files afterwards.

Tip: Please read more in the section covering the «a» command, found in the previous part of this page.

How do I add many files with a specific extension? Use the «a» command and the wildcard * symbol, but specify the extension after the wildcard. For example, *.txt means all text files. You can use the wildcard anywhere.

How can I add many files from an entire subdirectory? Specify just the directory name. You do not need to use a wildcard. The 7-Zip manual helpfully shows this example. It specifies an entire directory called «subdir».

7z a -tzip archive.zip subdir\

7z:          use executable
a:           add to archive
-tzip:       use zip compression
archive.zip: create this archive
subdir\:     source directory

Formats. This section answers questions about choosing formats. First, to use GZip compression, please specify the «-tgzip» option for the type switch. This makes a great way to compress files on your web server for HTTP compression.

7-Zip DEFLATE

How do I use BZip2? You can use BZip2 by specifying the «-tbzip2» switch. This can be combined with any compression level in the above charts. The different modes in 7-Zip automatically use many different settings.

How do I use 7z format? By specifying the «-t7z» switch for type. Or you can simply omit the type switch and that will default to 7z. This format offers the greatest compression ratios, but it does not work in all places.

Prompts. You can stop 7-Zip from displaying prompts. Please use the -y switch. This will assume a yes answer to all prompts. Use this only when you are confident that you are not going to lose any data.

Questions. There are many more possibilities and usages of the 7-Zip program on the command line in both Windows and Linux. This section answers some questions I had when doing this research, and also some questions that you may have.

Why can’t I update my archive? It is probably a solid archive. 7z archives are by default solid archives—all the files are compressed together. Change the archive not to be solid if you want to update it. Search this page for «solid».

Can I specify the output directory? Yes—please use the «e» command and combine it with the -o switch. The syntax with -o is a bit funny so I will show the example from the 7-Zip help file. Here’s how it works.

7z e archive.zip -oC:\soft *.cpp -r

7z:          executable
e:           use extract command
archive.zip: source archive you want to extract from
-oC:\soft:   the destination folder
	     (-o is the switch and C:\soft is the argument)
*.cpp:       only extract cpp files (C++)
-r:          traverse all subdirectories

How can I see what’s inside an archive? Use the «l» command as shown above. You might want to use «l» in a utility that you run from a command line to make sure your batch archiving properly works.

How can I exclude certain files? Near the start we saw how to add files based on filters, but sometimes you want to manually exclude certain files. Use the -x switch, followed immediately with an exclamation mark and then the filename.

So: If you want to exclude «file1.txt», use the switch «-x!file1.txt». Please include the hyphen and exclamation.

How can I replace files already on disk with new files? By using the -ao switch, described above. There are other options, and it is usually a better idea to use one of the renaming options (-aou or -aot).

Can I ignore extracting files already on disk? Yes—please specify the -aos option, which means «skip overwriting files.» This will cause 7za.exe to not copy the newer files out of the archive.

Note: Use -aos if your files don’t change over time and overwriting would just be a waste.

Embed. You can embed 7-Zip in a Windows .NET program using the tutorial in my article about .NET 7-Zip. This yields the same great compression but in your own GUI. The link shows some compression ratios.

7-Zip Executable

Internal settings. You can change internal settings. You do not need to do this normally, as they are set automatically. I recommend just using the mx=0 (and 3, 5, 7, 9) settings. An in-depth study would be fascinating.

What values can I change in the internals? You can change compression filters, which change behaviors on executable files such as *.exe and *.dll. You can enable header compression and encryption (-mhc=on and -mhe=on).

Tip: Header compression is by default enabled. Encryption must be explicitly enabled.

AdvanceCOMP. You can use AdvanceCOMP to improve compression ratios. The improvement is often small, less than 1%. 7-Zip and AdvanceCOMP use the same Deflate encoder, but AdvanceCOMP has more options and is more fine-grained.

AdvanceCOMP

Summary. 7-Zip can be used on the command line. This provides superior compression with an open-source tool. We created new archives, added to existing archives, used different formats for compression, and used various strengths of compression.


Related Links

Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf

Command Line Syntax

7z <command> [<switch>...] <base_archive_name> [<arguments>...]
<arguments> ::= <switch> | <wildcard> | <filename> | <list_file>
<switch>::= <switch_symbol><switch_characters>[<option>]
<switch_symbol> ::= '/' | '-' 
<list_file> ::= @{filename}

Expressions in square brackets (between ‘[‘ and ‘]’) are optional.

Expressions in curly braces (‘{‘ and ‘}’) mean that instead of that
Expression (including braces), the user must substitute some string.

Expression

expression1 | expression2 | ... | expressionN

means that any (but only one) from these expressions must be specified.

Commands and
switches can be entered in upper or lower case.

Command is the first non-switch argument.

The «base_archive_name» must be the first filename on the command line
after the command.

The switches and other filenames can be in any order.

Wildcards or filenames with spaces must be quoted:

    "Dir\Program files\*"
    Dir\"Program files"\*

Switch options can be combined to save command line length. However, some
switch options take optional string arguments and therefore, must be the
last option in a combined argument token string because 7-Zip accepts the
rest of the argument token as the optional argument.

7-Zip uses wild name matching similar to Windows 95:

  • ‘*’ means a sequence of arbitrary characters.
  • ‘?’ means any character.

7-Zip doesn’t uses the system wildcard parser. 7-Zip doesn’t
follow the archaic rule by which *.* means any file. 7-Zip treats
*.* as matching the name of any file that has an extension. To process all files, you must
use a * wildcard.

Examples:

*.txt means all files with an extension of «.txt»
?a* means all files with a second character of «a»
*1* means all names that contains character «1»
*.*.* means all names that contain two «.» means characters

The default wildcard «*» will be used if there is no filename/wildcard in the
command line.

Slash (‘\’) at the end of a path means a directory. Without a Slash (‘\’) at
the end of the path, the path can refer either to a file or a directory.

List file

You can supply one or more filenames or wildcards for special list files
(files containing lists of files). The filenames in such list file must be
separated by new line symbol(s).

For list files, 7-Zip uses UTF-8 encoding by default. You can change encoding
using -scs switch.

Multiple list files are supported.

For example, if the file «listfile.txt» contains the following:

    My programs\*.cpp
    Src\*.cpp

then the command

    7z a -tzip archive.zip @listfile.txt

adds to the archive «archive.zip» all «*.cpp» files from directories «My
programs» and «Src».

Short and Long File Names

7-Zip supports short file names (like FILENA~1.TXT) in some cases.
However, it’s strongly recommended to use only the real (long) file names.

7zip is a powerful and user-friendly package manager offering support for most popular file archives including ZIP, RAR, TAR, GZIP, 7z, and more. If you like you can also use the software without the GUI and access all features directly from the terminal. Discover best 7zip command line examples.

7z.exe is the command-line tool version of 7-Zip software allowing you to execute popular commands from system terminal. Use this app to compress, extract, test, rename, list, add, update archive files. This version works only with Windows. p7zip is the command line version of 7-Zip for Linux and Unix.

7z format provides a high compression ratio, open architecture, strong AES-256 encryption, option to use any compression or encryption method, supports files with sizes up to 16000000k GB, and Unicode file names. Integrated compression methods include LZMA, BCJ, Bzip2, Deflate, and PPMD.

7zip command line

The default compression method used by 7z format is LZMA. It features high compression ratio, variable dictionary size (up to 4 GB), small memory requirements for decompressing, support for multi-threading and P4’s hyper-threading, and fas compression and decompression speeds.

7z.exe offers access to over 10 commands for file operations. Moreover, there are also switches that can be used with commands to set password, type of archive, create SFX, update files, etc.

Usage: 7z <command> [<switches>…] <archive_name> [<file_names>…] [@listfile]

7-Zip command line add files to archive:

Compress folder Program Files to c:\filename.7z

7z.exe a c:\filename.7z "c:\Program Files"

7-Zip command line compress:

Compress folder, and subfolders in Program to c:\filename.7z

7z.exe a -r c:\filename.7z "c:\Program"

7-Zip command line pack all files:

Compress all JPG files in folder and subfolders from folder1

7z.exe a -r c:\filename.zip c:\folder1\*.jpg

7zip command line extract:

Extract all files from archive.zip

7z.exe e archive.zip

7zip command to extract specific file type:

Extract all .doc files from archive.zip to folder c:/kuba

7z.exe e archive.zip -o c:\kuba *.doc -r

7-Zip command line to calculate a hash (CRC32, CRC64, SHA1, SHA256, BLAKE2sp):

Calculate SHA256 hash value for file.iso.

7z.exe h -scrcsha256 file.iso

7-Zip command line benchmark:

Start benchmark.

7z.exe b

7-Zip command line list:

Show list of all files in the archive.

7z.exe l archive.zip

7-Zip command line rename:

Rename old.txt to new.txt and 101.txt to folder\101new.txt

7z.exe rn a.7z old.txt new.txt 101.txt folder\101new.txt

7-Zip commands quick reference

-a (Add)
-b (Benchmark)
-d (Delete)
-e (Extract)
-h (Hash)
-i (Show information about supported formats)
-l (List)
-rn (Rename)
-t (Test)
-u (Update)
-x (eXtract with full paths)

7-Zip switches for use with commands

-- : Stop switches and @listfile parsing
-ai[r[-|0]]{@listfile|!wildcard} : Include archives
-ax[r[-|0]]{@listfile|!wildcard} : eXclude archives
-ao{a|s|t|u} : set Overwrite mode
-an : disable archive_name field
-bb[0-3] : set output log level
-bd : disable progress indicator
-bs{o|e|p}{0|1|2} : set output stream for output/error/progress line
-bt : show execution time statistics
-i[r[-|0]]{@listfile|!wildcard} : Include filenames
-m{Parameters} : set compression Method
-mmt[N] : set number of CPU threads
-mx[N] : set compression level: -mx1 (fastest) ... -mx9 (ultra)
-o{Directory} : set Output directory
-p{Password} : set Password
-r[-|0] : Recurse subdirectories
-sa{a|e|s} : set Archive name mode
-scc{UTF-8|WIN|DOS} : set charset for for console input/output
-scs{UTF-8|UTF-16LE|UTF-16BE|WIN|DOS|{id}} : set charset for list files
-scrc[CRC32|CRC64|SHA1|SHA256|*] : set hash function for x, e, h commands
-sdel : delete files after compression
-seml[.] : send archive by email
-sfx[{name}] : Create SFX archive
-si[{name}] : read data from stdin
-slp : set Large Pages mode
-slt : show technical information for l (List) command
-snh : store hard links as links
-snl : store symbolic links as links
-sni : store NT security information
-sns[-] : store NTFS alternate streams
-so : write data to stdout
-spd : disable wildcard matching for file names
-spe : eliminate duplication of root folder for extract command
-spf : use fully qualified file paths
-ssc[-] : set sensitive case mode
-sse : stop archive creating, if it can't open some input file
-ssw : compress shared files
-stl : set archive timestamp from the most recently modified file
-stm{HexMask} : set CPU thread affinity mask (hexadecimal number)
-stx{Type} : exclude archive type
-t{Type} : Set type of archive
-u[-][p#][q#][r#][x#][y#][z#][!newArchiveName] : Update options
-v{Size}[b|k|m|g] : Create volumes
-w[{path}] : assign Work directory. Empty path means a temporary directory
-x[r[-|0]]{@listfile|!wildcard} : eXclude filenames
-y : assume Yes on all queries

Command Line Syntax

7z <command> [<switch>...] <base_archive_name> [<arguments>...]
<arguments> ::= <switch> | <wildcard> | <filename> | <list_file>
<switch>::= <switch_symbol><switch_characters>[<option>]
<switch_symbol> ::= '/' | '-' 
<list_file> ::= @{filename}

Expressions in square brackets (between ‘[‘ and ‘]’) are optional.

Expressions in curly braces (‘{‘ and ‘}’) mean that instead of that
Expression (including braces), the user must substitute some string.

Expression

expression1 | expression2 | ... | expressionN

means that any (but only one) from these expressions must be specified.

Commands and
switches can be entered in upper or lower case.

Command is the first non-switch argument.

The «base_archive_name» must be the first filename on the command line
after the command.

The switches and other filenames can be in any order.

Wildcards or filenames with spaces must be quoted:

    "Dir\Program files\*"
    Dir\"Program files"\*

Switch options can be combined to save command line length. However, some
switch options take optional string arguments and therefore, must be the
last option in a combined argument token string because 7-Zip accepts the
rest of the argument token as the optional argument.

7-Zip uses wild name matching similar to Windows 95:

  • ‘*’ means a sequence of arbitrary characters.
  • ‘?’ means any character.


7-Zip doesn’t use the system wildcard parser. 7-Zip doesn’t
follow the archaic rule by which *.* means any file. 7-Zip treats
*.* as matching the name of any file that has an extension. To process all files, you must
use a * wildcard.

Examples:

*.txt means all files with an extension of «.txt»
?a* means all files with a second character of «a»
*1* means all names that contains character «1»
*.*.* means all names that contain two at least «.» characters

The default wildcard «*» will be used if there is no filename/wildcard in the
command line.

Slash (‘\’) at the end of a path means a directory. Without a Slash (‘\’) at
the end of the path, the path can refer either to a file or a directory.

List file

You can supply one or more filenames or wildcards for special list files
(files containing lists of files). The filenames in such list file must be
separated by new line symbol(s).

For list files, 7-Zip uses UTF-8 encoding by default. You can change encoding
using -scs switch.

Multiple list files are supported.

For example, if the file «listfile.txt» contains the following:

    My programs\*.cpp
    Src\*.cpp

then the command

    7z a -tzip archive.zip @listfile.txt

adds to the archive «archive.zip» all «*.cpp» files from directories «My
programs» and «Src».

Short and Long File Names

7-Zip supports short file names (like FILENA~1.TXT) in some cases.
However, it’s strongly recommended to use only the real (long) file names.

Other documents on this site:

  • 7-Zip Manual /7zC.txt
  • 7-Zip Manual /readme.txt
  • 7-Zip Manual /copying.txt
  • 7-Zip Manual /lzma.txt
  • 7-Zip Manual /Methods.txt
  • 7-Zip Manual /unRarLicense.txt
  • 7-Zip Manual /License.txt
  • 7-Zip Manual /src-history.txt
  • 7-Zip Manual /7zFormat.txt
  • 7-Zip Start Page
  • Menu Items and Shortcut Keys
  • 7-Zip File Manager
  • Benchmark
  • Options Dialog Box
  • About Dialog Box
  • Plugins
  • Extract Dialog Box
  • 7-Zip Plugin
  • Add to Archive Dialog Box
  • Exit Codes from 7-Zip
  • Command Line Version User’s Guide
  • Command Line Syntax
  • -y (assume Yes on all queries) switch
  • -so (write data to stdout) switch
  • -ai (Include archive filenames) switch
  • -scc (Set charset for console input/output) switch
  • -w (set Working directory) switch
  • -bb (Set output log level) switch
  • -sni (Store NT security information) switch
  • -t (set Type of archive) switch
  • -ssc (Set Sensitive Case mode) switch
  • -ssw (Compress files open for writing) switch
  • -stx (Exclude archive type) switch
  • -si (read data from stdin) switch
  • -sns (Store NTFS alternate Streams) switch
  • -spf (Use fully qualified file paths) switch
  • — (Stop switches parsing) switch
  • -x (Exclude filenames) switch
  • Command Line Switches
  • -ax (Exclude archive filenames) switch
  • -r (Recurse subdirectories) switch
  • -sfx (Create SFX archive) switch
  • -i (Include filenames) switch
  • -slp (Set Large Pages mode) switch
  • -an (Disable parsing of archive_name) switch
  • -stl (Set archive timestamp from the most recently modified file) switch
  • -sa (set Archive name mode) switch
  • -scrc (Set hash function) switch
  • -ao (Overwrite mode) switch
  • -o (set Output directory) switch
  • -u (Update options) switch
  • -m (Set compression Method) switch
  • -spf (Use fully qualified file paths) switch
  • -scs (Set charset for list files) switch
  • -p (set Password) switch
  • -slt (Show technical information) switch
  • -sdel (Delete files after including to archive) switch
  • -v (Create Volumes) switch
  • d (Delete) command
  • rn (Rename) command
  • b (Benchmark) command
  • l (List contents of archive) command
  • e (Extract) command
  • Command Line Commands
  • a (Add) command
  • t (Test integrity of archive) command
  • u (Update) command
  • h (Hash) command
  • x (Extract with full paths) command
  • Performance
  • Thanks
  • Frequently Asked Questions (FAQ)
  • 7z Format
  • General Information
  • License for use and distribution
  • Supported formats

  • 7 zip для windows 7 torrent
  • 403 forbidden при скачивании windows 11
  • 629 ошибка pppoe windows 10
  • 8004e00f com ошибка windows 10
  • 7themes su оформление windows 10