bash 如何在各个子文件夹中找到所有 tar 文件,然后将它们解压缩到它们找到的同一文件夹中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29279197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 12:39:34  来源:igfitidea点击:

How to find all tar files in various sub-folders, then extract them in the same folder they were found?

linuxbashautomationcentostar

提问by user1942651

I have lots of sub-folders, with only some containing a tar file. i.e.:

我有很多子文件夹,只有一些包含 tar 文件。IE:

folder1/
folder2/this-is-a.tar
folder3/
folder4/this-is-another.tar

I can find which dirs have the tar by simply doing ls */*.tar.

我可以通过简单地找到哪些目录有 tar ls */*.tar

What I want to achieve is somehow find all .tar files, then extract them in the same directory they are found, then delete the .tars.

我想要实现的是以某种方式找到所有 .tar 文件,然后将它们解压缩到它们找到的同一目录中,然后删除 .tars。

I've tried ls */*.tar | xargs -n1 tar xvfbut that extracts the tars in in the directory I'm in, not the directory the tars were found.

我已经尝试过,ls */*.tar | xargs -n1 tar xvf但是它会在我所在的目录中提取 tars,而不是找到 tars 的目录。

Any help would be greatly appreciated.

任何帮助将不胜感激。

回答by guido

for i in */*.tar ; do pushd `dirname $i` ; tar xf `basename $i` && rm `basename $i` ; popd ; done

Edit: this is probably a better way:

编辑:这可能是更好的方法:

find . -type f -iname "*.tar" -print0 -execdir tar xf {} \; -delete

回答by Blagovest Buyukliev

for file in */*.tar; do
    (cd `dirname $file`; tar xvf `basename $file`)
    unlink $file
done