使用 bash 从 tar.gz 中提取 1 个文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3470063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 19:34:41  来源:igfitidea点击:

Extract 1 file from tar.gz with bash

linuxbashgziptar

提问by TJ L

Is it possible to programmatically pull a single file from a decently sized .tar.gz without extracting the entire tarball to disk? Essentially I need to get inside large tar.gz files over the network and extract 1 small text file. It seems somewhat over-the-top to pull and extract the tarball to disk, then pull the file out, then delete everything else. Also I'm going to be doing this recursively (e.g. package dependencies, each text file points to more tar.gz's), so the less network traffic and cpu cycles I can get away with, the better.

是否可以以编程方式从大小合适的 .tar.gz 中提取单个文件而不将整个 tarball 提取到磁盘?基本上我需要通过网络进入大型 tar.gz 文件并提取 1 个小文本文件。将 tarball 拉出并解压缩到磁盘,然后将文件拉出,然后删除其他所有内容似乎有些过分。此外,我将递归地执行此操作(例如,包依赖项,每个文本文件指向更多的 tar.gz),因此我可以摆脱的网络流量和 CPU 周期越少越好。

回答by Cascabel

From the man page, to extract blah.txt from foo.tar.gz:

从手册页中,从 foo.tar.gz 中提取 blah.txt:

tar -xzf foo.tar.gz blah.txt

(And this goes on superuser, of course, but hey, prompt answers are nice too.)

(当然,超级用户也是如此,但是嘿,提示的答案也很好。)

回答by Chance

I echo Jefromi's answer, with the addition of including the path to the file if you have directories in the tar file (this may seem obvious to some, but it wasn't initially clear to me how to specify the directory structure).

我回应 Jefromi 的回答,如果您在 tar 文件中有目录,则添加文件的路径(这对某些人来说似乎很明显,但最初我不清楚如何指定目录结构)。

For example, if you did the tar at the src/ directory, and blah.txt was under release1/shared/, you would go back to the src/ directory (if you want it untarred at the same place)

例如,如果你在 src/ 目录下做了 tar,而 blah.txt 在 release1/shared/ 下,你会回到 src/ 目录(如果你想在同一个地方解压)

tar -xzf tar.gz release1/shared/blah.txt

If you don't remember the directory structure of your tar file (I'm a little disorganized and sometimes forget where I did the tar), you can always

如果你不记得你的 tar 文件的目录结构(我有点混乱,有时会忘记我在哪里做的 tar),你总是可以

tar -tzf tar.gz

to see the contents, canceling out (Ctrl+C) once you get an idea of your directory structure.

查看内容,一旦您了解目录结构,就取消 (Ctrl+C)。