tar – extract discarding directory structure

Solution 1:

GNU tar lives on featuritis, so naturally also has some options for that.
http://www.gnu.org/software/tar/manual/html_node/transform.html

If you just want to remove a few path segments, then --strip-components=n or --strip=n will often do:

 tar xvzf tgz --strip=1

But it's also possible to regex-rewrite the files to be extracted (flags are --transform or --xform and accept ereg with the /x modifer):

 tar xvzf tgz --xform='s#^[^/]+#.#x'
                 # or 's#^.+/##x' for discarding all paths

For listing a tar you need the additional --show-transformed option:

 tar tvzf tgz --show-transformed --strip=1 --xform='s/abc/xyz/x'

I believe the rewriting options also work for packing, not just for extracting. But pax has obviously a nicer syntax.

Solution 2:

You can do it fairly easily in two steps. Adapt as necessary:

$ mkdir /tmp/dirtree
$ tar xfz /path/to/archive -C /tmp/dirtree
$ find /tmp/dirtree -type f -exec mv -i {} . \;
$ rm -rf /tmp/dirtree

Solution 3:

pax can do it:

pax -v -r -s '/.*\///p' < archive.tar

or

zcat archive.tar.gz | pax -v -r -s '/.*\///p'

You can check the name replacement operation first by omitting the -r option.

Solution 4:

A possible solution that doesn't require installing anything.

  1. use a tar tvf to grab all the files from the tarball
  2. Extract those files individually - have tar extract to stdout & redirect to $filename

    tar -tvf $1 | grep -v "^d" | \
                  awk '{for(i=6;i<NF+1;i++) {printf "%s ",$i};print ""}' |\
                  while read filename
                  do
                     tar -O -xf $1 "$filename" > `basename "$filename"`
                  done
    

save as extract.sh and run as extract.sh myfile.tar. It will also overwrite any duplicate filenames encountered in the directories pulled from the tarball.