Tar how to extract tar gz
Tar how to extract tar gz
How to Extract or Unzip tar.gz Files from Linux Command Line
Home » DevOps and Development » How to Extract or Unzip tar.gz Files from Linux Command Line
A tar.gz file contains several compressed files to save storage space, as well as bandwidth during the downloading process. The .tar file acts as a portable container for other files and is sometimes called a tarball. The .gz part of the extension, stands for gzip, a commonly-used compression utility.
In this guide you will learn how to extract or unzip files from tar.gz files using command-line in Linux.
Extracting tar.gz Files in Linux
Using gzip Utility
Gzip by default, extracts the file in the current directory. In this example the file is located in the Documents directory.
Below, we have used the file named test.txt. Use the name of the file you want to compress instead.
to compress a single file with gzip enter the command in your terminal window:
After zipping the file, enter the command ls to confirm that the file has been compressed. The output confirms that the file now has a .gz extension.
To decompress a file, use the gunzip command:
Again, use the ls command to confirm the extension of the file.
The * sign is a wildcard, which means “any number of any characters.” This command would work on any (and all) filenames with the extension .txt.
When you run gzip on multiple files at once, the system generates a compressed copy of each file. This can clutter up a directory quickly! Fortunately, there’s another tool to manage multiple files at once.
Using tar Utility
A tar.gz file is a combination of a .tar file and a .gz file. It is an archive file with several other files inside it, which is then compressed.
You can unzip these files the same way you would unzip a regular zipped file:
To list the contents of a .tar file before you extract it, enter:
To instruct tar to put the extracted unzipped files into a specific directory, enter:
To create a tar.gz file, use the following command:
Similar to the tar command, it condenses all the content located in the /home/user/Documents directory into a single file, called documents.tar.gz. The addition of the –z option is what signals tar to compress the files.
To add multiple files to a tar file, use the command:
This copies the contents of your Documents folder into a single file, called documents.tar. The options -cvf work as follows:
Команда tar в Linux
В качестве инструмента для архивации данных в Linux используются разные программы. Например архиватор Zip Linux, приобретший большую популярность из-за совместимости с ОС Windows. Но это не стандартная для системы программа. Поэтому хотелось бы осветить команду tar Linux — встроенный архиватор.
Изначально tar использовалась для архивации данных на ленточных устройствах. Но также она позволяет записывать вывод в файл, и этот способ стал широко применяться в Linux по своему назначению. Здесь будут рассмотрены самые распространенные варианты работы с этой утилитой.
Синтаксис команды tar
Синтаксис команд для создания и распаковки архива практически не отличается (в том числе с утилитами сжатия bzip2 или gzip). Так, чтобы создать новый архив, в терминале используется следующая конструкция:
tar опции архив.tar файлы_для_архивации
Для его распаковки:
tar опции архив.tar
Функции, которые может выполнять команда:
Функция | Длинный формат | Описание |
---|---|---|
-A | —concatenate | Присоединить существующий архив к другому |
-c | —create | Создать новый архив |
-d | —diff —delete | Проверить различие между архивами Удалить из существующего архива файл |
-r | —append | Присоединить файлы к концу архива |
-t | —list | Сформировать список содержимого архива |
-u | —update | Обновить архив более новыми файлами с тем же именем |
-x | —extract | Извлечь файлы из архива |
При определении каждой функции используются параметры, которые регламентируют выполнение конкретных операций с tar-архивом:
Параметр | Длиннный формат | Описание |
---|---|---|
-C dir | —directory=DIR | Сменить директорию перед выполнением операции на dir |
-f file | —file | Вывести результат в файл (или на устройство) file |
-j | —bzip2 | Перенаправить вывод в команду bzip2 |
-p | —same-permissions | Сохранить все права доступа к файлу |
-v | —verbose | Выводить подробную информацию процесса |
—totals | Выводить итоговую информацию завершенного процесса | |
-z | —gzip | Перенаправить вывод в команду gzip |
А дальше рассмотрим примеры того, как может применяться команда tar Linux.
Как пользоваться tar
1. Создание архива tar
С помощью следующей команды создается архив archive.tar с подробным выводом информации, включающий файлы file1, file2 и file3:
Но длинные опции и параметры можно заменить (при возможности) однобуквенными значениями:
2. Просмотр содержимого архива
Следующая команда выводит содержимое архива, не распаковывая его:
3. Распаковка архива tar Linux
Распаковывает архив test.tar с выводом файлов на экран:
Чтобы сделать это в другой каталог, можно воспользоваться параметром -C:
3. Работа со сжатыми архивами
Следует помнить, что tar только создаёт архив, но не сжимает. Для этого используются упомянутые компрессорные утилиты bzip2 и gzip. Файлы, сжатые с их помощью, имеют соответствующие расширения .tar.bz2 и .tar.gz. Чтобы создать сжатый архив с помощью bzip2, введите:
Синтаксис для gzip отличается одной буквой в параметрах, и меняется окончание расширения архива:
При распаковке tar-архивов с таким расширением следует указывать соответствующую опцию:
На заметку: архиватор tar — одна из немногих утилит в GNU/Linux, в которой перед использованием однобуквенных параметров, стоящих вместе, можно не ставить знак дефиса.
Выводы
В этой статье была рассмотрена команда tar Linux, которая используется для архивации файлов и поставляется по умолчанию во всех дистрибутивах. В её возможности входит создание и распаковка архива файлов без их сжатия. Для сжатия утилита применяется в связке с популярными компрессорами bzip2 и gzip.
How to extract filename.tar.gz file
9 Answers 9
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
If file filename.tar.gz gives this message: POSIX tar archive, the archive is a tar, not a GZip archive.
Or try a generic Unpacker like unp (https://packages.qa.debian.org/u/unp.html), a script for unpacking a wide variety of archive formats.
determine the file type:
As far as I can tell, the command is correct, ASSUMING your input file is a valid gzipped tar file. Your output says that it isn’t. If you downloaded the file from the internet, you probably didn’t get the entire file, try again.
Without more knowledge of the source of your file, nobody here is going to be able to give you a concrete solution, just educated guesses.
I have the same error the result of command :
is hadoop-2.7.2.tar.gz: HTML document, ASCII text
the reason that the file is not gzip format due to problem in download or other.
Internally tar xcvf will call the binary gzip from the PATH environment variable to decompress the files in the tar archive. Sometimes third party tools use a custom gzip binary which is not compatible with the tar binary. It is a good idea to check the gzip binary in your PATH with which gzip and make sure that a correct gzip binary is called.
Check to make sure that the file is complete. This error message can occur if you only partially downloaded a file or if it has major issues. Check the MD5sum.
The other scenario you mush verify is that the file you’re trying to unpack is not empty and is valid.
In my case I wasn’t downloading the file correctly, after double check and I made sure I had the right file I could unpack it without any issues.
Как извлечь (разархивировать) файл Tar Gz
How to Extract (Unzip) Tar Gz File
Команда tar используется для создания архивов tar путем преобразования группы файлов в архив. Он поддерживает широкий спектр программ сжатия, таких как gzip, bzip2, lzip, lzma, lzop, xz и compress. Изначально Tar был предназначен для создания архивов для хранения файлов на магнитной ленте, поэтому он имеет название « T ape AR chive».
Короче говоря, файл, который заканчивается на .tar.gz, является архивом .tar, сжатым с помощью gzip.
Извлечение файла tar.gz
-v Опция сделает tar команду более заметной и напечатать имена файлов извлекаются на терминале.
Например, чтобы извлечь содержимое архива в /home/linuxize/files каталог, вы можете использовать:
Извлечение определенных файлов из файла tar.gz
Чтобы извлечь определенный файл (ы) из файла tar.gz, добавьте разделенный пробелами список имен файлов, которые будут извлечены после имени архива:
Извлечение одного или нескольких каталогов из архива аналогично извлечению файлов:
Если вы попытаетесь извлечь файл, который не существует, появится сообщение об ошибке, подобное следующему:
Извлечение файла tar.gz из stdin
В следующем примере мы загружаем исходные тексты Blender с помощью wget команды и направляем их вывод в tar команду:
Если вы не укажете опцию декомпрессии, tar укажите, какую опцию вам следует использовать:
Перечисление файла tar.gz
Вывод будет выглядеть примерно так:
10 Tar command examples in Linux to create and extract archives
Tar command on Linux
The tar (tape archive) command is used to create and extract archives in Linux. It can compress and store multiple files in a single archive.
In this tutorial we shall take a look at simple examples of using the tar command to do daily jobs of creating and extracting archives on linux desktops or servers.
Using the tar command
The tar command is available by default on most linux systems and you do not need to install it separately.
1. Extract a tar.gz archive
Well, the more common use is to extract tar archives. The following command shall extract the files out a tar.gz archive
Those are some of the important options to memorise
Extract tar.bz2/bzip archives
Files with extension bz2 are compressed with the bzip algorithm and tar command can deal with them as well. Use the j option instead of the z option.
2. Extract files to a specific directory or path
To extract out the files to a specific directory, specify the path using the «-C» option. Note that its a capital C.
However first make sure that the destination directory exists, since tar is not going to create the directory for you and will fail if it does not exist.
3. Extract a single file
To extract a single file out of an archive just add the file name after the command like this
More than once file can be specified in the above command like this
4. Extract multiple files using wildcards
Wildcards can be used to extract out a bunch of files matching the given wildcards. For example all files with «.txt» extension.
5. List and search contents of the tar archive
If you want to just list out the contents of the tar archive and not extract them, use the «-t» option. The following command prints the contents of a gzipped tar archive,
Pipe the output to grep to search a file or less command to browse the list. Using the «v» verbose option shall print additional details about each file.
For tar.bz2/bzip files use the «j» option
Use the above command in combination with the grep command to search the archive. Simple!
6. Create a tar/tar.gz archive
Now that we have learnt how to extract existing tar archives, its time to start creating new ones. The tar command can be told to put selected files in an archive or an entire directory. Here are some examples.
The following command creates a tar archive using a directory, adding all files in it and sub directories as well.
The above example does not create a compressed archive. Just a plain archive, that puts multiple files together without any real compression.
In order to compress, use the «z» or «j» option for gzip or bzip respectively.
7. Ask confirmation before adding files
A useful option is «w» which makes tar ask for confirmation for every file before adding it to the archive. This can be sometimes useful.
Only those files would be added which are given a yes answer. If you do not enter anything, the default answer would be a «No».
8. Add files to existing archives
The r option can be used to add files to existing archives, without having to create new ones. Here is a quick example
9. Add files to compressed archives (tar.gz/tar.bz2)
Its already mentioned that its not possible to add files to compressed archives. However it can still be done with a simple trick. Use the gunzip command to uncompress the archive, add file to archive and compress it again.
For bzip files use the bzip2 and bunzip2 commands respectively.
10. Backup with tar
Ofcourse make sure that the disk space is not overflown with larger and larger archives.
11. Verify archive files while creation
The «W» option can be used to verify the files after creating archives. Here is a quick example.
Note that the verification cannot be done on compressed archives. It works only with uncompressed tar archives.
Conclusion
Besides the tar command, there are many other commands available on the linux command line that can be used to compress and pack files in an archive. For example the zip and unzip command can also be used to create compressed archives.