How to strip path while archiving with TAR

neversaint picture neversaint · Nov 7, 2011 · Viewed 34.6k times · Source

I have a file that contain list of files I want to archive with tar. Let's call it mylist.txt

It contains:

/path1/path2/file1.txt
/path1/path2/file3.txt
...
/path1/path2/file10.txt

What I want to do is to archive this file into a tarball but excluding /path1/path2/. Currently by doing this:

tar -cvf allfiles.tar -T mylist.txt

preserves the path after unarchiving.

I tried this but won't work too:

tar -cvf -C /path1/path2 allfiles.tar -T mylist.txt

It archives all the files in /path1/path2 even those which are not in mylist.txt

Is there a way to do it?

Answer

hovanessyan picture hovanessyan · Nov 7, 2011

In your "Extraction phase" you can use the strip-components flag like

tar xvf tarname.tar --strip-components=n

which will remove the first n leading components of the file name. Although if you have different file-path-components this will not work for all cases.

If you want to do it while archiving, only one thing comes to mind, and I will share

INPUT: list of files + full paths

1) for each line, split the path out of the filename

2) execute cd to that path and tar on that filename

3) repeat for each line