Showing posts with label tar. Show all posts
Showing posts with label tar. Show all posts

Wednesday, September 28, 2011

Linux commands for Compressing and Archiving File

1. gzip and gunzip
gzip command is used to compress the file, and gunzip is used to de-compress it.
Usage:
gzip <file name>
It provides the extension .gz and removes the original file
Example:
$ wc sample_copy.txt
      65 2776 17333 sample_copy.txt
$ gzip sample_copy.txt
$ wc sample_copy.txt.gz
      26 155 7095 sample_copy.txt.gz

The compression ratio depends on the type, size and nature of the file

Usage:
gunzip <file name with.gz>
Example:
$ gunzip sample_copy.txt.gz
$ /*do ls and you can see the original file*/

If you want to compress the directory contents recursively, use -r option with gzip command and unzip it use the same option with gunzip command.

2. tar : The archival program
tar command is used to create archive that contains a group or file or entire directory structure.
It is generally used for back ups.
Usage:
tar [options] <file1 or dir> . . .

Options:
  • -c Create an archive
  • -x Extract files from archive
  • -t Display files in archive
  • -f arch Name the archive arch
Examples:
$ tar -cvf compression.tar compression
compression/ //v for verbose
compression/temp/
compression/temp/sample2.txt
compression/sample1.txt
  • We can use tar and gzip command in succession to compress the tar file.
$ tar -cvf compression.tar compression
$ gzip compression.tar
$ //will create compression.tar.gz file
  • For un-compression the file first use gunzip command, which will create a tar file and then use tar command to untar the contents
$ gunzip compression.tar.gz
$ tar -xvf compression.tar
  • To just view the contents of the tar file use -t option 
$ tar -tvf compression.tar
  • Instead of doing tar first and then gzip next, we can combine both of them using the option -z
$ tar -cvzf compression.tar.gz compression
compression/
compression/temp/
compression/temp/sample2.txt
compression/sample1.txt
  •  We can de-compress .tar.gz agin in a single command using the option -z with -x
$ tar -xvzf compression.tar.gz
 3. zip and unzip: compressing and archiving
zip command can be used for archiving as well as compressing the contents of the directory or the file.
Usage:
zip [options] output.zip <files to be zipped or directory>
Example:
$ zip sample1.zip sample1.txt
//will create sample1.zip file
  • Use -r option to recursively zip the contents of the directory
$ zip -r compression.zip compression
// will create compression.zip file
  • To un-compress the file use unzip command 
$ unzip compression.zip
// will uncompress the compression.zip file