11

I have the following four files in the file system:

/home/martin/cvs/ops/cisco/b/s1
/home/martin/cvs/ops/cisco/b/s2
/home/martin/cvs/ops/extreme/b/r3
/home/martin/cvs/ops/j/b/r5

I need to put those files into a tar archive, but I don't want to add directories. The best I could come up with was:

tar -C ~/cvs/ops/ -czvf archive.tgz cisco/b/s1 cisco/b/s2 extreme/b/r3 j/b/r5

This is still not perfect, because each file in the archive is two directories deep. Is there a better way? Or do I simply have to copy s1, s2, r3 and r5 files into one directory and create the archive with tar -czvf archive.tgz s1 s2 r3 r5?

17

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).

11

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.

8

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.

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.