43

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?

Ulrich Eckhardt
  • 16,572
  • 3
  • 28
  • 55
si_2012
  • 649
  • 1
  • 6
  • 11

5 Answers5

41

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
suspectus
  • 16,548
  • 8
  • 49
  • 57
19

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.

yatsek
  • 855
  • 1
  • 10
  • 19
4

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

Shirish Singh
  • 797
  • 7
  • 17
0

To extract files from one directory to second directory while keeping the filename in the second directory i.e without the complete file path and file extension

%sh
for file in /mnt/dir1/*.tar.gz; 
do 
y=${file##*/}; 
z=${y%%.*}; 
mkdir -p /mnt/dir2/$z && tar -xzvf $file -C /mnt/dir2/$z;
done
puligun
  • 332
  • 3
  • 12
-4

Well, if you run $ tar -zxf some-archive.tar.gz -C ., (note the dot at the end) a new directory called some-archive/ will be created in the directory you are currently in.

Maybe this is what you meant by your question? This is what I generally want so it may work for you as well.

Felipe
  • 11,557
  • 7
  • 56
  • 103
  • 1
    While this is true, it doesn't answer the question. `-C .` is redundant because the default output directly is the current directory anyway. – David Cook Feb 24 '19 at 22:50