26

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?

neversaint
  • 60,904
  • 137
  • 310
  • 477

1 Answers1

38

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

hovanessyan
  • 30,580
  • 6
  • 55
  • 83
  • 19
    thanks. I'm aware of `strip-components`. However still prefer stripping while archiving. – neversaint Nov 07 '11 at 23:06
  • 2
    The "cd & tar, then cd & tar" sounds a lot like the examples in [the tar manual on "Changing the Working Directory" at gnu.org](http://www.gnu.org/software/tar/manual/html_node/directory.html) using -C in the "middle" of a command line to cd & add following files from that dir, with multiple -C & more files, all added to the "root" of the tar. Can even put `-C/path` lines in `--files-from` file lists – Xen2050 Apr 20 '17 at 07:21
  • 2
    @Xen2050 Nailed this on the head. `tar -cf output.tar -C /path/to target_directory` did what I needed. Thanks! – Henry Rivera Jan 17 '19 at 04:12
  • 4
    note, the `-C` parameter does not work if you're attempting to specify a wildcard. If you have a bunch of images in `/home/me/images` and you try `tar -czf mypictures.tar.gz -C /home/me/images *.jpg` it will fail (shell expansion expands the wildcard before the tar command is run, so it populates with any .jpg files in the current directory). – Doktor J Sep 16 '19 at 21:18