I need to search for a file inside a tar.gz
file without extracting it. After that, I need to copy the file that was searched (if ever there is) to another folder.
So far I have this, but the copy part of this line gives me an error.
gunzip -c file.tar.gz | tar tvf - | grep filename | -exec cp {} /folder/another_folder \;
Or is there a better way to search for a file inside a tar.gz
file without extracting it?
Best Answer
Does your version of
tar
not support the switch-z
?This would then return the name of the file if it existed at all in the archive.
Extracting the file
You could do something like this if you wanted to search for the file first, and only if present then extract it.
Sample Tarball
Example
Confirmation
A different directory
If you want to output the extracted file to some other location you can use
tar
's-C
switch.Example #1
Confirmation
Example #2
Confirmation
Example #3
Wildcards could also be used if you want to extract a pattern of files.
Confirmation
Details
The above involves a couple of additional changes. We're extracting everything that matches
'*Makefile'
. Notice that we've wrapped it in single quotes vs. double quotes now. This is to protect the*Makefile
from getting accidentally expanded.grep
now includes the switch-E
, because we're searching for a regular expression now and not just a single string within the output oftar
. Also the argument togrep
is also not wrapped in double quotes.We now use the switch
--wildcards
to the 2ndtar
so that we can extract based on a pattern rather than just a single file. This argument too is now wrapped in double quotes to protect it.