tar -C with a wildcard file pattern

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.


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'

The accepted answer assumes the files are taken from a single directory. If you use multiple -C options, then you need a more general approach. The following command has the shell expand the file names, which are then passed to tar.

tar -cf example.tar -C /path/to/file $(cd /path/to/file ; echo *.xml)

Tags:

Linux

Tar