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


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:


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


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


    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.


With GNU tar (found on non-embedded Linux and Cygwin), you can apply a regular expression replacement to the paths when adding members to an archive or when extracting them with the --transform option.

tar -xf foo.tar --transform='s!^/home/mydir/dir1/!!'

With *BSD tar (including on OSX), there's a similar option called -s.

tar -xf foo.tar -s '!^/home/mydir/dir1/!!'

POSIX has the pax command with the same option as BSD tar.

pax -r <foo.tar -s '!^/home/mydir/dir1/!!'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.