Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract files contained in archive.tar.gz to new directory named archive

Tags:

tar

I have a directory containing about 800 .tgz archives, each containing about 10 files. Effectively, I want to convert each archive into a directory of the same name. Is there a simple one line command to do this, or should I write a script?

like image 457
si_2012 Avatar asked Feb 21 '13 16:02

si_2012


People also ask

How do I extract files from tar gz?

Simply right-click the item you want to compress, mouseover compress, and choose tar. gz. You can also right-click a tar. gz file, mouseover extract, and select an option to unpack the archive.

How do I extract an archive file in Linux?

To extract an archive, use the tar -xf command followed by the archive name, and to create a new one use tar -czf followed by the archive name and the files and directories you want to add to the archive.

Which of the following commands will correctly extract files from an archive named Foo tar gz that has been created using tar gzip?

gz file is a Tar archive compressed with Gzip. To extract a tar. gz file, use the tar -xf command followed by the archive name.


3 Answers

Update since GNU tar 1.28: use --one-top-level, see https://www.gnu.org/software/tar/manual/tar.html#index-one_002dtop_002dlevel_002c-summary

Older versions need to script this. You can specify the directory that the extract is placed in by using the tar -C option.

The script below assumes that the directories do not exist and must be created. If the directories do exist the script will still work - the mkdir will simply fail.

tar -xvzf archive.tar.gx -C archive_dir

e.g.

for a in *.tar.gz
do
    a_dir=${a%.tar.gz}
    mkdir --parents $a_dir
    tar -xvzf $a -C $a_dir
done
like image 132
suspectus Avatar answered Sep 26 '22 06:09

suspectus


If modern enough GNU tar is being taken into account then this should be top answer here: https://unix.stackexchange.com/a/478341/34069

For brevity this is extract:

tar -xvf bash.html_node.tar.gz --one-top-level

It extracts archive into new directory named after archive file name.

like image 15
yatsek Avatar answered Sep 25 '22 06:09

yatsek


Create a folder in which you want to extract like this mkdir archive and pass folder name with -C while extracting, tar -xvf archive.zip -C archive

like image 4
Shirish Singh Avatar answered Sep 26 '22 06:09

Shirish Singh