How to extract all tar.gz files present in multiple folders at a time to another directory?
16,200
Use find
and execute a command on each found file, in the directory of that file:
find . -name '*.tar.gz' -execdir tar -xzvf '{}' \;
The -execdir
option executes tar
from within the folder of the found file, and {}
will be replaced by the tarfile's name.
See the find
documentation for more info.
Related videos on Youtube
Author by
beginner
Updated on September 18, 2022Comments
-
beginner over 1 year
There are many folders in my current directory. Each folder has a tar.gz file. To extract the tar.gz file I need to be inside each folder and run the following command every time.
tar xvzf tar.gz -C /path/to/targetdirectory
Inside my current directory it looks like below:
current directory ├──Folder1 ├── A.tar.gz ├──Folder2 ├── B.tar.gz ├──Folder3 ├── C.tar.gz ├──Folder4 ├── D.tar.gz ├──Folder5 ├── E.tar.gz
To extract all at a time I tried like this
tar xvzf */*.tar.gz -C /path/to/targetdirectory
This gave me an error:
tar: Folder1/A.tar.gz: Not found in archive tar: Folder2/B.tar.gz: Not found in archive tar: Folder3/C.tar.gz: Not found in archive tar: Folder4/D.tar.gz: Not found in archive tar: Folder5/E.tar.gz: Not found in archive
-
beginner about 6 yearsWhere should I give target directory in the command?
-
beginner about 6 yearsOk. Gave like this to get the extracted files into target directory. find . -name '*.tar.gz' -execdir tar -C /path/to/targetdirectory -xzvf '{}' \; This worked
-
slhck about 6 yearsYep, you can specify the commands as usual within the
-exec
option. -
beginner about 6 yearshi...I have small doubt. Is there a way to give path to those...*.tar.gz files?
-
slhck about 6 yearsYou can
find
in another directory by replacingfind .
withfind /path/to/directory
. -
metabuddy about 2 yearsHere is the complete cmd using different search directory and different target directory: find /var/www/staging/ -name '*.tar.gz' -execdir tar -C /var/www/target -xzf ' {}' \; Thanks slhck and beginner for help, this works very well.