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?
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
-
Yes, I thought I would probably need a script - thanks for the confirmation.– si_2012Feb 21, 2013 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.
-
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. Jun 15, 2020 at 18:01 -
3@IanSmith - ok, good point - but you mean probably "it does not exist in BSD version ..."– yatsekJun 17, 2020 at 10:16
-
-
5The option --one-top-level was added to GNU tar in version 1.28, released 2014-07-28, see release notes here: gnu.org/software/tar Oct 18, 2020 at 8: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
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
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.
-
1While this is true, it doesn't answer the question.
-C .
is redundant because the default output directly is the current directory anyway. Feb 24, 2019 at 22:50
tar -xvzf filename.tar.gz -C /desired/path
mkdir -p dirpath && tar xzf archive.tar.gz -C dirpath