Home > Software engineering >  unzipping all .tgz files in folder to a specific folder
unzipping all .tgz files in folder to a specific folder

Time:09-09

I am new to linux and I am trying the following:

I have directory data. In this directory there are x files that end with *.tgz. I want to unpack each, and store the output in a new folder. So as an example. I start with:

ls data

folder_a.tgz    folder_b.tgz    folder_c.tgz

I want want to end up with:

ls /data/test/
folder_a    folder_b    folder_c

I have tried the following:

ls *.tgz | xargs -n1 tar zxvf -C /data/test/

Which gives the error:

-C cannot open: no such file or directory

I do not understand why this does not work, since these both work as expected:

tar zxvf folder_a.tgz -C /data/test/
ls *.tgz | xargs -n1 tar zxvf

But combining these does not work. Can anyone help me to achieve the goal, and maybe explain why my solution does not work?

CodePudding user response:

Your problem is that xargs puts the argument at the end, but tar requires the filename after the f flag. The following should work:

ls *.tgz | xargs -n1 tar zxv -C /data/test/ -f

But maybe just using a loop will be the better solution here:

for ARCHIVE in *.tgz; do tar xvzf "$ARCHIVE" -C /data/test; done

or alternatively:

ls *.tgz | while read ARCHIVE; do tar xvzf "$ARCHIVE" -C /data/test; done
  • Related