Score:4

How can I extract files in the directory where they're located with the find command?

kg flag

I have tried to extract multiple files from the directory where they're located with:

for i in $(find . -name '*.tgz'); do  # search the tgz files and extract them
    tar -xvzf $i
done

I expected that the command would extract these files within the directory they were found in, however they are extracted outside their directory. How can I make sure that the .tgz files are extracted in the directory where they are located?

Score:8
hr flag

You should avoid constructions like for i in $(find . -name '*.tgz'); do ... - see for example Why is looping over find's output bad practice? - instead, use -exec or -execdir to run the command directly on found files whenever possible.

For your application, -execdir will do exactly what you want i.e. execute tar relative to each .tgz file's containing directory:

find . -name '*.tgz' -execdir tar -xvf {} \;

See also Understanding the -exec option of find.

Score:4
id flag

You need to look at the tar man page: man tar

Found in man tar

   -C, --directory=DIR
          Change to DIR before performing any operations.  This option  is
          order-sensitive, i.e. it affects all options that follow.

And using a command that will give you the directory name of a path is dirname. Then you could add on to your command -C $(dirname $i) to extract to the directory that the tar file was found in. So, you would just change your command to:

for i in $(find . -name '*.tgz'); do
    tar -xvzf $i -C $(dirname $i)
done
Mina Michael avatar
in flag
Good job, that indeed works! @Cook4733 I hope you can mark his answer as the accepted answer.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.