Tar extract into directory with same base name

tar

I have a ziped file like myArchive123.tar.gz. Inside it contains a folder like helloWorld

If I extract it: tar -xf myArchive123.tar.gz I get the helloWorld folder:

ls 
myArchive123.tar.gz
helloWorld 

I would like the output to be the same name as the file name minus the .tar.gz extension. I.e:

tar <magic paramaters> myArchive123.tar.gz 
ls 
 myArchive123.tar.gz
 myArchive123
cd myArchive123
ls 
  helloWorld

Can this be done?

  • I never know what's inside the archive. Could be a folder, could be many files.
  • I'd be ok with using another tool if tar can't do it.
  • I'd be ok with a longer form that can be turned into a script

EDIT
In the mean time I hacked myself a script that seems to get the job done. (see my posted answer below). If it can be improved, please feel free to post comments/additional answers.
The main thing is that it should be packagable into a one-liner like:

extract <file>

Best Answer

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
Related Question