如何递归 tar+gzip 具有特定名称的文件夹?

如何递归 tar+gzip 具有特定名称的文件夹?

我有一个带有多个嵌套文件夹的大型文件结构。我想用特定名称 tar+gzip 压缩每个文件夹并删除原始文件夹。

在此示例中,我希望脚本能够检测以 结尾的每个文件夹.abc,并对该文件夹进行 tar+gzip,删除原始文件夹并保留 .gz。

Main Folder/
    Project 1/
        Prj1FolderA.abc/
            ...lots of tiny files and maybe subfolders...
        Prj1FolderB.abc/
            ...lots of tiny files and maybe subfolders...
        Prj1FolderC.abc/
            ...lots of tiny files and maybe subfolders...
    Project 2/
        Prj2FolderA.abc/
            ...lots of tiny files and maybe subfolders...
        Prj2FolderB.abc/
            ...lots of tiny files and maybe subfolders...
        Prj2FolderC.abc/
            ...lots of tiny files and maybe subfolders...
    Project 3/
        Prj3FolderA.abc/
            ...lots of tiny files and maybe subfolders...
        Prj3FolderB.abc/
            ...lots of tiny files and maybe subfolders...
        Prj3FolderC.abc/
            ...lots of tiny files and maybe subfolders...
    Project 4/
        Another Folder Inside/
            Prj4FolderA.abc/
                ...lots of tiny files and maybe subfolders...
            Prj4FolderB.abc/
                ...lots of tiny files and maybe subfolders...
            Prj4FolderC.abc/
                ...lots of tiny files and maybe subfolders...

运行此脚本后,我希望该文件夹如下所示:

Main Folder/
    Project 1/
        Prj1FolderA.abc.tar.gz
        Prj1FolderB.abc.tar.gz
        Prj1FolderC.abc.tar.gz
    Project 2/
        Prj2FolderA.abc.tar.gz
        Prj2FolderB.abc.tar.gz
        Prj2FolderC.abc.tar.gz
    Project 3/
        Prj3FolderA.abc.tar.gz
        Prj3FolderB.abc.tar.gz
        Prj3FolderC.abc.tar.gz
    Project 4/
        Another Folder Inside/
            Prj4FolderA.abc.tar.gz
            Prj4FolderB.abc.tar.gz
            Prj4FolderC.abc.tar.gz

这只是一个示例,文件夹的名称可能与上面不完全一样,也不是全部都是 2 层深度。其间可能有多个文件夹。

我假设使用find来执行此操作,但我不太确定如何将正确的信息传递到tar并删除原始文件夹。谢谢!

答案1

在以下位置运行Main Folder

find . -type d -name '*.abc' -exec sh -c '
    for d; do tar -C "$d" -zcf "$d.tar.gz" . && rm -r "$d"; done
' findsh {} +

虽然我测试过,但我建议您也测试一下。在echo前面加上一个rm,这样如果出现问题,您就不会丢失数据。

内部循环执行tarand rm(仅当tar成功时)找到与“*.abc”全局模式匹配的子目录。

相关内容