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?
-
You can specify that in the command itself `tar -xvzf filename.tar.gz -C /desired/path` – Aravind.HU Feb 21 '13 at 17:30
-
4-C will not work if dir does not exists. Better run: `mkdir -p dirpath && tar xzf archive.tar.gz -C dirpath` – Noam Manos Sep 03 '18 at 14:47
5 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

- 52
- 5

- 16,548
- 8
- 49
- 57
-
Yes, I thought I would probably need a script - thanks for the confirmation. – si_2012 Feb 21 '13 at 17:59
-
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.

- 855
- 1
- 10
- 19
-
No it shouldn't, `--one-top-level does` not exist in the GNU version of tar. Meaning it's not supported on OSX and some versions of Linux. – Ian Smith Jun 15 '20 at 18:01
-
2@IanSmith - ok, good point - but you mean probably "it does not exist in BSD version ..." – yatsek Jun 17 '20 at 10:16
-
-
4The option --one-top-level was added to GNU tar in version 1.28, released 2014-07-28, see release notes here: https://www.gnu.org/software/tar/ – Johannes Müller Oct 18 '20 at 08:22
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

- 797
- 7
- 17
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

- 332
- 3
- 12
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.

- 11,557
- 7
- 56
- 103
-
1While 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