tar -C 带有通配符文件模式

Nic*_* C. 22 linux tar

我可以使用 tar 命令更改目录并使用通配符文件模式吗?

这是我想要做的:

tar -cf example.tar -C /path/to/file *.xml
Run Code Online (Sandbox Code Playgroud)

如果我不更改目录 (-C),它会起作用,但我正在尝试避免 tar 文件中的绝对路径。

tar -cf example.tar /path/to/file/*.xml
Run Code Online (Sandbox Code Playgroud)

以下是我所做的其他一些尝试:

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"
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误:

tar: *.xml: Cannot stat: No such file or directory
Run Code Online (Sandbox Code Playgroud)

我知道还有其他方法可以使这项工作(使用 find、xargs 等),但我希望仅使用 tar 命令来完成此操作。

有任何想法吗?

Maj*_*nko 21

问题是,*.xml 由 shell 解释,而不是由 tar 解释。因此,它找到的 xml 文件(如果有)位于您运行 tar 命令的目录中。

您必须使用多阶段操作(可能涉及管道)来选择所需的文件,然后对它们进行 tar。

最简单的方法就是cd进入文件所在的目录:

$ (cd /path/to/file && tar -cf /path/to/example.tar *.xml)
Run Code Online (Sandbox Code Playgroud)

应该管用。

括号将命令组合在一起,因此当它们完成时,您仍将位于原始目录中。&& 表示tar只有在初始cd成功时才会运行。


小智 11

在您的一项尝试中:

tar -cf example.tar -C /path/to/file "*.xml"
Run Code Online (Sandbox Code Playgroud)

* 字符确实传递给了 tar。然而,问题在于 tar 仅支持对档案成员名称进行通配符匹配。因此,虽然在从存档中提取或列出成员时可以使用通配符,但在创建存档时不能使用通配符。

在这种情况下,我经常求助于 find (就像你已经提到的那样)。如果你有 GNU find,它有一个很好的选项来打印相对路径,使用 -printf 选项:

find '/path/to/file' -maxdepth 1 -name '*.xml' -printf '%P\0' \
| tar --null -C '/path/to/file' --files-from=- -cf 'example.tar'
Run Code Online (Sandbox Code Playgroud)


Dio*_*lis 8

接受的答案假设文件是​​从单个目录中获取的。如果您使用多个-C选项,那么您需要更通用的方法。以下命令让 shell 扩展文件名,然后将其传递给tar

tar -cf example.tar -C /path/to/file $(cd /path/to/file ; echo *.xml)
Run Code Online (Sandbox Code Playgroud)