如何使用tar提取没有文件夹结构的文件

Ben*_*son 50 php unix linux tar

我有一个tar.gz文件,其结构如下:

folder1/img.gif
folder2/img2.gif
folder3/img3.gif
Run Code Online (Sandbox Code Playgroud)

我想提取没有文件夹层次结构的图像文件,因此提取的结果如下所示:

/img.gif
/img2.gif
/img3.gif
Run Code Online (Sandbox Code Playgroud)

我需要结合Unix和PHP来做到这一点.这是我到目前为止,它的工作原理是将它们提取到指定的目录,但保留文件夹层次结构:

exec('gtar --keep-newer-files -xzf images.tgz -C /home/user/public_html/images/',$ret);
Run Code Online (Sandbox Code Playgroud)

eri*_*icg 94

您可以使用tar 的--strip-components选项.

 --strip-components count
         (x mode only) Remove the specified number of leading path ele-
         ments.  Pathnames with fewer elements will be silently skipped.
         Note that the pathname is edited after checking inclusion/exclu-
         sion patterns but before security checks.
Run Code Online (Sandbox Code Playgroud)

我创建了一个与您的结构类似的tar文件:

$tar -tf tarfolder.tar
tarfolder/
tarfolder/file.a
tarfolder/file.b

$ls -la file.*
ls: file.*: No such file or directory
Run Code Online (Sandbox Code Playgroud)

然后通过做提取:

$tar -xf tarfolder.tar --strip-components 1
$ls -la file.*
-rw-r--r--  1 ericgorr  wheel  0 Jan 12 12:33 file.a
-rw-r--r--  1 ericgorr  wheel  0 Jan 12 12:33 file.b
Run Code Online (Sandbox Code Playgroud)

  • 我尝试使用比包含的目录结构更高的数字,它也删除了文件。因此,您必须知道要删除的目录的确切数量。 (4认同)
  • 条带组件是否有您可以使用的最大数量?如果 .tar 只包含一个文件夹的层次结构,而 strip-components 是 2,会发生什么?此外,strip-components 是否会更改这些图像文件的名称或只是删除文件夹? (3认同)
  • 我建议您使用它,并根据您的具体情况确定它是否对您有用。 (2认同)
  • 这太棒了!但只有一件事是,如果我们不知道要剥离多少个组件怎么办?我们只想获取文件而不获取文件夹? (2认同)

for*_*ord 19

使用-transform标志只能使用tar,这几乎是可能的,但据我所知,没有办法删除左侧目录.

这将使整个存档变平:

tar xzf images.tgz --transform='s/.*\///'
Run Code Online (Sandbox Code Playgroud)

输出将是

folder1/
folder2/
folder3/
img.gif
img2.gif
img3.gif
Run Code Online (Sandbox Code Playgroud)

不幸的是,您将需要使用其他命令删除目录.

  • 在 RHEL 6.2 上,[接受的答案](http://stackoverflow.com/a/14295994/86263) 不起作用,但这个答案起作用(即使在_创建_存档时)。:) 好极了! (2认同)

Min*_*mul 12

检查tar版本,例如

$ tar --version
Run Code Online (Sandbox Code Playgroud)

如果版本> =而不是tar-1.14.90使用--strip-components

tar xvzf web.dirs.tar.gz -C /srv/www --strip-components 2
Run Code Online (Sandbox Code Playgroud)

否则使用 --strip-path

tar xvzf web.dirs.tar.gz -C /srv/www --strip-path 2
Run Code Online (Sandbox Code Playgroud)