iT邦幫忙

0

Bzip2 Command in Linux with Examples

Today you will learn how to compress files in Linux using bzip2 command.

What is File Compression?

File compression is a method by which we can save disk space by reducing the size of available data. A compressed file is a collection in which one or more files are stored.

We have several ways in Linux by which you can compress files and directories. The most popular tools are:

  • gzip
  • bzip2
  • zip

In this guide, we are going to discuss the complete features of bzip2 command with examples.

bzip2 is the most popular compression tool among other similar tools used to compress files only.

But by combining it with the tar command, you can also compress directories.

Features of bzip2 Command:

  • Compress and Decompress (Extract) a File
  • Reduces file size
  • Display the contents of a compressed file
  • Tests compressed file integrity
  • Concatenate the contents of multiple files.

How to identify a bzip2 file?

You can identify the bzip2 file by its extension. The file extension of bzip2 is .bz2.

1. Compress a File

To compress a file using bzip2 type the following command.

Here I am compressing a file named file.txt.

~$ bzip2 file.txt

Output:

~$ ls
file.txt.bz2

2. Compress multiple Files

You can compress multiple files using bzip2.

To compress multiple files, pass the file names to bzip2. Here I am compressing files named file.txt, file1.txt, file2.txt, file3.txt, file4.txt

~$ bzip2 file.txt file1.txt file2.txt file3.txt file4.txt

Output:

~$ ls
file1.txt.bz2  file2.txt.bz2  file3.txt.bz2  file4.txt.bz2  file.txt.bz2

You can also use wildcards with bzip2. Let’s take some examples:

Ex. # 1 Compress those files whose extension is “.txt“.

~$ bzip2 *.txt

Ex. # 2 Compress those files that start with “fi“.

~$ bzip2 fi*

3. Compress a file Forcefully

To compress a file forcefully pass the -z option to bzip2.

~$ bzip2 -z file.txt

4. Keep (Don’t delete) input Files

bzip2 by default deletes the input file after compressing.

But if you want to keep the input files during compression, then pass the -k option to bzip2.

~$ bzip2 -k file.txt

Output:

~$ ls
file.txt  file.txt.bz2

By the way, the -c option helps to concatenate the contents of multiple files.

But you can also use this option to keep input files while compressing.

Here is an example.

Syntax:

bzip2 -c [INPUT FILE] > [OUTPUT FILE]

~$ bzip2 -c file.txt > newfile.txt.bz2

Now type the following command to concatenate the contents of the two files.

Here in this example, I am concatenating the contents of file.txt and file1.txt.

~$ bzip2 -c file1.txt >> newfile.txt.bz2

Now to decompress the file type the following command.

~$ bzip2 -d newfile.txt.bz2

Output:

~$ ls
newfile.txt
~$ cat newfile.txt 
Linux is a Open Source Operating System.
I Love Linux.

Read complete article Here


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言