tar extract into directory with same base name?

With gnu tar, you could use --xform (or --transform) to prepend /prefix/ to each file name:

tar -xf myArchive.tar.gz --xform='s|^|myArchive/|S'

note there's no leading / in prefix/ and the sed expression ends with S to exclude symbolic link targets from file name transformations.
To test it (dry-run):

tar -tf myArchive.tar.gz --xform='s|^|myArchive/|S' --verbose --show-transformed-names

To get you started, here's a very simplistic script that you could invoke as extract <file>:

STRIP=${1%.*}                                #strip last suffix
NAME=${STRIP%.tar}                           #strip .tar suffix, if present
tar -xf "$1" --xform="s|^|$NAME/|S"          #run command

Well, you could do it in a couple of steps at least. If you did

mkdir <archive name>
tar -xf <archive name>.tar.gz --strip-components=1 -C <archive name>

that would accomplish the task, though there may be a more compact answer out there yet.


Edit

The accepted answer is shorter than the below. (do the same thing, but shorter is usually better).


I eventually hacked myself a script for the task at hand. it works with .tar .tar.gz and .gz

#!/bin/sh
#usage:
# nameOfScript myArchive.tar.gz
# nameOfScript myArchive.gz
# nameOfScript myArchive.tar
#
# Result:
# myArchive   //folder
fileName="${1%.*}" #extracted filename

#handle the case of archive.tar.gz
trailingExtension="${fileName##*.}"
if [ "$trailingExtension" == "tar" ]  
then
    fileName="${fileName%.*}"  #remove trailing  tar.
fi

mkdir "$fileName"
tar -xf "$1" --strip-components=0 -C "$fileName"

Usage:

   nameOfScript archive.tar.gz 
   ls 
    archive
   cd archive 
   ls 
    <archive content>

Note, this solution is capable of dots in a file name. E.g Eclipse-4.5M-SDK.tar.gz.

I keep the script in my git repo. For the latest version, see: https://github.com/LeoUfimtsev/ldts/blob/master/pathscripts/leo-tar-here

Tags:

Tar