Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

up vote 6 down vote accepted

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.

share|improve this answer
    
Thanks for the great explanation. –  Nick C. Apr 4 '11 at 14:42

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'
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.