- How to Extract Tar Files to Specific or Different Directory in Linux
- Example 1: Extracting tar Files to a Specific Directory
- Example 2: Extract .tar.gz or .tgz Files to Different Directory
- Example 3: Extract tar.bz2, .tar.bz, .tbz or .tbz2 Files to Different Directory
- Example 4: Extract Only Specific or Selected Files from Tar Archive
- Summary
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- Команда tar в Linux
- Синтаксис команды tar
- Как пользоваться tar
- 1. Создание архива tar
- 2. Просмотр содержимого архива
- 3. Распаковка архива tar Linux
- 3. Работа со сжатыми архивами
- Выводы
- How do I extract with tar to a different directory?
- 7 Answers 7
- Not the answer you’re looking for? Browse other questions tagged tar or ask your own question.
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
- Linux tar Command and How To Tar A Directory
- Create Archive with Linux tar
- Compress While Archiving
- List Files in Tar Archive
- Extract Single File From Archive
- Extract Multiple Files From Archive with tar
- Untar Command
- Adding File into Archive
- Estimate Archive Size
- Linux tar Command and How To Tar A Directory Infografic
How to Extract Tar Files to Specific or Different Directory in Linux
The tar utility is one of the utilities that you can use to create a backup on a Linux system. It includes many options that one can use to specify the task to achieve.
Extract Linux Tar Files Different or New Directory
One thing to understand is that you can extract tar files to a different or specific directory, not necessarily the current working directory. You can read more about tar backup utility with many different examples in the following article, before proceeding further with this article.
In this guide, we shall take a look at how to extract tar files to a specific or different directory, where you want the files to reside.
The general syntax of tar utility for extracting files:
Note: In the above first syntax, the -C option is used to specify a different directory other than the current working directory.
Let us now look at some examples below.
Example 1: Extracting tar Files to a Specific Directory
In the first example, I will extract the files in articles.tar to a directory /tmp/my_article . Always make sure that the directory into which you want to extract tar file exists.
Let me start by creating the /tmp/my_article directory using the command below:
You can include the -p option to the above command so that the command does not complain.
To extract the files in articles.tar to /tmp/my_article , I will run the command bellow:
Img 01: Extract Tar Files to Different Directory
In the above example I used the -v option to monitor the progress of the tar extraction.
Let me also use the —directory option instead of -c for the example above. It works just in the same way.
Img 02: Extract Tar Files to Specific Directory
Example 2: Extract .tar.gz or .tgz Files to Different Directory
First make sure that you create the specific directory that you want to extract into by using:
Now we will extract the contents of documents.tgz file to separate /tmp/tgz/ directory.
Img 03: Extract tar.gz or .tgz Files to Different Directory
Example 3: Extract tar.bz2, .tar.bz, .tbz or .tbz2 Files to Different Directory
Again repeating that you must create a separate directory before unpacking files:
Now we will be unpacking the documents.tbz2 files to /tmp/tar.bz2/ directory.
Img 04: Extract tar.bz2 Files to Different Directory
Example 4: Extract Only Specific or Selected Files from Tar Archive
The tar utility also allows you to define the files that you want to only extract from a .tar file. In the next example, I will extract specific files out of a tar file to a specific directory as follows:
Img 05: Extract Specific Files From Tar Archive
Summary
That is it with extracting tar files to a specific directory and also extracting specific files from a tar file. If you find this guide helpful or have more information or additional ideas, you can give me a feedback by posting a comment.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник
Команда 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:
tar —totals —create —verbose —file archive.tar file1 file2 file3
Но длинные опции и параметры можно заменить (при возможности) однобуквенными значениями:
tar —totals -cvf archive.tar file1 file2 file3
2. Просмотр содержимого архива
Следующая команда выводит содержимое архива, не распаковывая его:
tar -tf archive.tar
3. Распаковка архива tar Linux
Распаковывает архив test.tar с выводом файлов на экран:
tar -xvf archive.tar
Чтобы сделать это в другой каталог, можно воспользоваться параметром -C:
tar -C «Test» -xvf archive.tar
3. Работа со сжатыми архивами
Следует помнить, что tar только создаёт архив, но не сжимает. Для этого используются упомянутые компрессорные утилиты bzip2 и gzip. Файлы, сжатые с их помощью, имеют соответствующие расширения .tar.bz2 и .tar.gz. Чтобы создать сжатый архив с помощью bzip2, введите:
tar -cjvf archive.tar.bz2 file1 file2 file3
Синтаксис для gzip отличается одной буквой в параметрах, и меняется окончание расширения архива:
tar -czvf archive.tar.gz file1 file2 file3
При распаковке tar-архивов с таким расширением следует указывать соответствующую опцию:
tar -C «Test» -xjvf arhive.tar.bz2
tar -xzvf archive.tar.gz
На заметку: архиватор tar — одна из немногих утилит в GNU/Linux, в которой перед использованием однобуквенных параметров, стоящих вместе, можно не ставить знак дефиса.
Выводы
В этой статье была рассмотрена команда tar Linux, которая используется для архивации файлов и поставляется по умолчанию во всех дистрибутивах. В её возможности входит создание и распаковка архива файлов без их сжатия. Для сжатия утилита применяется в связке с популярными компрессорами bzip2 и gzip.
Источник
How do I extract with tar to a different directory?
This doesn’t work:
It’s not obvious to me what would do this beyond extracting it in place and moving the files over.
7 Answers 7
if you want to extract an tar archive elsewhere just cd to the destination directory and untar it there:
The command you’ve used would search the file foo/bar in the archive and extract it.
would do the job.
Basically, what is does is spawning a new shell (the parentheses), in this subshell, change directory to foo/bar and then untar the file.
You can change the ; by a && to be sure the cd works fine.
tar -xzvf foo.tar.gz -C /home/user/bar/
will extract the input file «foo.tar.gz», into the directory /home/user/bar , while printing the processed files.
Change the directory where you want to extract
if location of the extract file under /u01/backup.tar then
Extract as follows:
you can give file name with ./file after tar file.
if it is working means you have created a tar with ./ . use less command to see tar content.
I ran into what seems to be a similar issue and have resolved it.
The issue was in the file creation rather than the created file.
When attempting to tar up and transfer a file in dir A, I provided the path to the original file in the tar command
What I was able to do to resolve is
On transferring and extracting the tarball, the required subdirs are created.
Not the answer you’re looking for? Browse other questions tagged tar or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.10.8.40416
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Источник
Linux tar Command and How To Tar A Directory
Old days of Unix to make backups into tape archives tar utility was used. The days past and Linux become popular in UNIX world. But the popularity of tar is never ended. tar is used compress and extract files. We will look usage examples of tar in this tutorial. Tar command is similar to the Windows zip. We can call this for Linux zip folder. There are alternative ways to compress files but we will look tar Linux.
Create Archive with Linux tar
Generally used to make multiple files and directories one file. We will tar a directory
- c for compress but actually it is not compressed
- v for verbosity to see what happens
- f for archive file name
- dymerge.tar is new tar file name
- dymerge is the source directory name
Compress While Archiving
We can compress archived with with z parameter. z is used to gzip format
- z is for gzip compression other options are default for our usage
To compress with bzip2 j parameter should be provided.
List Files in Tar Archive
We can list files without opening the tar. t parameter is used to list. But if the archive is gzip we should provide z too. As we see tar.gz is extension for tarred and gzipped files.
- t list files
- z archive is gzip format
List Files in Tar Archive
If the archive is bzip2 we can use following command
Extract Single File From Archive
With tar a single file can be extracted from archive. x is the parameter to be used for this operation
- dymerge.tar.gz is our archive that contains our single file
- dymerge/surnames.txt is the file we want to extract
Extract Multiple Files From Archive with tar
We can extract multiple files with tar. We need too provide –wildcards parameter and related files for this. Here * is used for globing
- –wildcards is the parameter
- *.txt is the file names we want to exract
Untar Command
We can create some alias to create new untar command like below.
Untar Command
Adding File into Archive
After creating an archive we may need to update or add new files and folders to the existing archive. We can use r option to add new file or folder by specifying file and folder names at the end of the command like below. In this example we will add file named test.txt into the existing archive named dymerge.tar.gz
- We append test.txt file with r option
- We can add directories too
Estimate Archive Size
Before archiving a directory with tar command we can learn the size of the archive with the help of wc command. We will tar the directory in to the starndard output which will be redirected to the wc command. wc command will count the bytes and provide estimated size of the given archived file.
Linux tar Command and How To Tar A Directory Infografic
Источник