如何使用shell脚本解压所有.tar.gz?

时间:2022-05-28 21:07:40

I tried this:

我试过这个:

DIR=/path/tar/*.gz

if [ "$(ls -A $DIR 2> /dev/null)" == "" ]; then
  echo "not gz"
else
  tar -zxvf /path/tar/*.gz -C /path/tar
fi

If the folder has one tar, it works. If the folder has many tar, I get an error.

如果文件夹有一个tar,它可以工作。如果文件夹有很多tar,我会收到错误。

How can I do this?

我怎样才能做到这一点?

I have an idea to run a loop to untar, but I don't know how to solve this problem

我有一个想法来运行循环来解压,但我不知道如何解决这个问题

4 个解决方案

#1


24  

for f in *.tar.gz
do
  tar zxvf "$f" -C /path/tar
done

#2


11  

I find the find exec syntax very useful:

我发现find exec语法非常有用:

find . -name '*.tar.gz' -exec tar -xzvf {} \;

找 。 -name'* .tar.gz'-exec tar -xzvf {} \;

{} gets replaced with each file found and the line is executed.

{}被替换为找到的每个文件并执行该行。

#3


3  

for a in /path/tar/*.gz
do
    tar -xzvf "$a" -C /path/tar
done

Notes

  • This presumes that files ending in .gz are gzipped tar files. Usually .tgz or .tar.gz is used to signify this, however tar will fail if something is not right.
  • 这假定以.gz结尾的文件是gzip压缩文件。通常.tgz或.tar.gz用于表示这一点,但是如果出现问题,tar将失败。
  • You may find it easier to cd /path/tar first, then you can drop the -C /path/tar from the untar command, and the /path/tar/ in the loop.
  • 您可能会发现首先更容易cd / path / tar,然后您可以从untar命令中删除-C / path / tar,并在循环中删除/ path / tar /。

#4


0  

The accepted answer worked for me with a slight modification

接受的答案对我有所改变

for f in *.tar.gz
do
  tar zxvf "$f" -C \name_of_destination_folder_inside_current_path
done

I had to change the forward slash to a backslash and then it worked for me.

我不得不将正斜杠改为反斜杠然后它对我有效。

#1


24  

for f in *.tar.gz
do
  tar zxvf "$f" -C /path/tar
done

#2


11  

I find the find exec syntax very useful:

我发现find exec语法非常有用:

find . -name '*.tar.gz' -exec tar -xzvf {} \;

找 。 -name'* .tar.gz'-exec tar -xzvf {} \;

{} gets replaced with each file found and the line is executed.

{}被替换为找到的每个文件并执行该行。

#3


3  

for a in /path/tar/*.gz
do
    tar -xzvf "$a" -C /path/tar
done

Notes

  • This presumes that files ending in .gz are gzipped tar files. Usually .tgz or .tar.gz is used to signify this, however tar will fail if something is not right.
  • 这假定以.gz结尾的文件是gzip压缩文件。通常.tgz或.tar.gz用于表示这一点,但是如果出现问题,tar将失败。
  • You may find it easier to cd /path/tar first, then you can drop the -C /path/tar from the untar command, and the /path/tar/ in the loop.
  • 您可能会发现首先更容易cd / path / tar,然后您可以从untar命令中删除-C / path / tar,并在循环中删除/ path / tar /。

#4


0  

The accepted answer worked for me with a slight modification

接受的答案对我有所改变

for f in *.tar.gz
do
  tar zxvf "$f" -C \name_of_destination_folder_inside_current_path
done

I had to change the forward slash to a backslash and then it worked for me.

我不得不将正斜杠改为反斜杠然后它对我有效。