首页 > 解决方案 > 仅排除 tar 命令中的特定文件夹

问题描述

我想 tar 一个看起来像这样的目录:

dir
└── workspace
└── node_modules
└── subfolder
    └── workspace
    └── node_modules
    └── other_folder

我想排除所有名为的文件夹node_modules并排除名为的顶级文件夹workspace,但不排除名为的子文件夹workspace。所以我想要结束的是:

dir
└── subfolder
    └── workspace
    └── other_folder

我正在运行这个命令:tar -czf ./output.tar.gz --exclude=node_modules --exclude=./workspace dir/.

但它正在删除所有名为 workspacenode_modules 的文件夹,所以我最终得到了这个:

dir
└── subfolder
    └── other_folder

如何仅删除我想要的特定工作区文件夹,而不是所有同名文件夹?

标签: shelltararchive

解决方案


对于所需的情况,可以使用 tar 排除:

  • --exclude dir/./folder-- 直接应用到dir下的文件夹
  • --exclude folder-- 将排除树中任何位置的文件夹

应该可以使用:

tar -czf ./output.tar.gz --exclude=node_modules --exclude=dir/./workspace dir/.

当然可以使用--files-from, 并使用其他工具生成列表。当列表可能包含大量文件时,这通常是首选,而不是使用xargs.

find dir/. -type f ... | tar cvz ./output.tar.gz -T-

推荐阅读