Extract and Compress 7z files in command line
7-Zip is a file archiver with a high compression ratio. The file compressed by 7-Zip has an extension ”.7z”. Here is a list of main features of 7-Zip, which is from its official website:
- High compression ratio in 7z format with LZMA and LZMA2 compression
- Supported formats:
- Packing / unpacking: 7z, XZ, BZIP2, GZIP, TAR, ZIP and WIM
- Unpacking only: AR, ARJ, CAB, CHM, CPIO, CramFS, DMG, EXT, FAT, GPT, HFS, IHEX, ISO, LZH, LZMA, MBR, MSI, NSIS, NTFS, QCOW2, RAR, RPM, SquashFS, UDF, UEFI, VDI, VHD, VMDK, WIM, XAR and Z.
- For ZIP and GZIP formats, 7-Zip provides a compression ratio that is 2-10 % better than the ratio provided by PKZip and WinZip
- Strong AES-256 encryption in 7z and ZIP formats
- Self-extracting capability for 7z format
- Integration with Windows Shell
- Powerful File Manager
- Powerful command line version
- Plugin for FAR Manager
- Localizations for 87 languages
To use 7z in command line we need to install it first.
Installation of 7-Zip on CentOS/RHEL:
# sudo yum info p7zip
Installation of 7-Zip on Ubuntu/Debian:
# sudo apt-get install p7zip-full
To extract / Create an 7z file:
$ 7z x archive.7z
To create a compressed file with 7-Zip:
$ 7za a -t7z ../archive.7z *
The command compresses all the files in currently directory, and generates a compressed file in upper directory. Note that the command we use is “7za”.
To remove a single file from an archive
We can also remove a single file from an archive with “d”. This is more useful when you do not have a solid archive.
7z d archive.zip *.bak -r
Then all the matched files (which has extension “.bak”) will be remove from archive, and “-r” traverses all subdirectories.
To create an encrypted file with 7-Zip
This can be done by the switch p. We 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.
$ 7za a pw.7z *.txt -pYOURSECRET
This command add all the *.txt files to destination archive, and specify the password “YOURSECRET”
To exclude certain files in compressing
Sometimes we want to manually exclude certain files. Use the -x switch, followed immediately with an exclamation mark and then the filename. If you want to exclude “file.txt”, use the switch “-x!file.txt”. Please include the hyphen and exclamation.