tar -C with a wildcard file pattern

18

3

Can I use the tar command to change directories and use a wildcard file pattern?

Here is what I am trying to do:

tar -cf example.tar -C /path/to/file *.xml

It works if I don't change directory (-C), but I'm trying avoid absolute paths in the tar file.

tar -cf example.tar /path/to/file/*.xml

Here are some of the other attempts I've made:

tar -cf example.tar -C /path/to/file *.xml
tar -cf example.tar -C /path/to/file/ *.xml
tar -cf example.tar -C /path/to/file/ ./*.xml
tar -cf example.tar -C /path/to/file "*.xml"

And this is the error I get:

tar: *.xml: Cannot stat: No such file or directory

I know there are other ways ways to make this work (using find, xargs, etc.) but I was hoping to do this with just the tar command.

Any ideas?

Nick C.

Posted 2011-04-04T14:10:01.277

Reputation: 283

Answers

18

The problem is, the *.xml gets interpreted by the shell, not by tar. Therefore the xml files that it finds (if any) are in the directory you ran the tar command in.

You would have to use a multi-stage operation (maybe involving pipes) to select the files you want and then tar them.

The easiest way would just be to cd into the directory where the files are:

$ (cd /path/to/file && tar -cf /path/to/example.tar *.xml)

should work.

The brackets group the commands together, so when they have finished you will still be in your original directory. The && means the tar will only run if the initial cd was successful.

Majenko

Posted 2011-04-04T14:10:01.277

Reputation: 29 007

9

In one of your attempts:

tar -cf example.tar -C /path/to/file "*.xml"

the * character is indeed passed to tar. The problem, however, is that tar only supports wildcard matching on the names of members of an archive. So, while you can use wildcards when extracting or listing members from an archive, you cannot use wildcards when you are creating an archive.

In such situations often I resort to find (like you mentioned already). If you have GNU find, it has the nice option to print only the relative path, using the -printf option:

find '/path/to/file' -maxdepth 1 -name '*.xml' -printf '%P\0' \
| tar --null -C '/path/to/file' --files-from=- -cf 'example.tar'

gaston

Posted 2011-04-04T14:10:01.277

Reputation: 231