Creating a tar archive without including the parent directory when files are stored in different directories

You can use -C multiple times (moving from one directory to another):

tar czvf archive.tar.gz -C /home/martin/cvs/ops/cisco/b s1 s2 -C ../../extreme/b r3 -C ../../j/b r5

Note that each -C option is interpreted relative to the current directory at that point (or you can just use absolute paths).


If you have the list of files in a file, or can generate them using a command, you can use a single GNU tar command:

tar cf foo.tar -T list-of-files --transform 's:.*/::'

The transform still keeps directories, but flattens the layout completely. So you need some way of filtering directories, hence the need of a list of files.


You could append files to the archive one by one:

tar cf /tmp/archive.tar -C /home/martin/cvs/ops/cisco/b s1
tar rf /tmp/archive.tar -C /home/martin/cvs/ops/cisco/b s2
tar rf /tmp/archive.tar -C /home/martin/cvs/ops/extreme/b r3
tar rf /tmp/archive.tar -C /home/martin/cvs/ops/j/b r5

You could script this to make it easier: for each path, run tar rf with the base directory as the value for the -C parameter and the base filename without path to add.

Tags:

Tar