Linux – How to untar a file skipping the beginning of the directory structure

archivelinuxtar

I created tar archives with an absolute path to save the files.

/home/mydir/dir1/dir2/dir3/file1.dat
/home/mydir/dir1/dir2/dir3/file2.dat
/home/mydir/dir1/dir2/dir3/file3.dat

I would like to untar these archives skipping the leading part of the path, /home/mydir/dir1. My files should be restored in any directory with this structure:

dir2/dir3/file1.dat
dir2/dir3/file2.dat
dir2/dir3/file3.dat

How can I do this with the tar command, or another way?

Best Answer

If you are using GNU tar, then there is an option to remove some leading path members when extracting:

 `--strip-components=number'

    Strip given number of leading components from file names before extraction.

For example, suppose you have archived whole `/usr' hierarchy to a
tar archive named `usr.tar'. Among other files, this archive
contains `usr/include/stdlib.h', which you wish to extract to the
current working directory. To do so, you type:

$ tar -xf usr.tar --strip=2 usr/include/stdlib.h

(From the GNU tar documentation.)

In your case, --strip=3 should apply.

Related Question