简体   繁体   English

如何从原位的tarball中删除空目录

[英]How to remove empty directories from a tarball in-place

I extracted a layer from a docker image which archived in a file called layer.tar. 我从docker映像中提取了一个图层,该映像存储在一个名为layer.tar的文件中。 I want to remove empty directories from it. 我想从中删除空目录。

I don't want to unpack then repack files in that archive, I want to keep the original info, so I want to do it in-place. 我不想解压缩然后重新打包该存档中的文件,我想保留原始信息,所以我想就地进行。

I know how to delete files from tar but I don't know any simple method to delete empty directories in-place. 我知道如何从tar删除文件,但是我不知道任何简单的方法可以就地删除空目录。

Let's create a archive t.tar with a/b/c/ and a/b/c/d/ empty directories: 让我们创建一个包含a/b/c/a/b/c/d/空目录的档案t.tar:

mkdir -p dir
cd dir
mkdir -p a/b/c/d
mkdir -p 1/2/3/4
touch a/fil_ea a/b/file_ab # directory a/b/c and a/b/c/d are empty
touch 1/2/3/file_123 1/2/3/4/file_1234 # directories 1/2/3/4 not empty
tar cf ../t.tar a 1
cd ..

Using tar tf and some filtering we can extract the directories and files in a tar archive. 使用tar tf和一些过滤,我们可以将目录和文件提取到tar归档文件中。 Then for each directory in tmpdirs we can check if it has any files in tmpfiles with a simple grep and then remove those directories using --delete tar option: 然后在每个目录tmpdirs我们可以检查是否有任何文件tmpfiles用一个简单的grep,然后删除使用这些目录--delete焦油选项:

tar tf t.tar | tee >(grep '/$' > tmpdirs) | grep -v '/$' > tmpfiles
cat tmpdirs | xargs -n1 -- sh -c 'grep -q "$1" tmpfiles || echo "$1"' -- \
  | tac \
  | xargs -- tar --delete -f t.tar

Not that tac is a bit unneeded, but the files where sorted alphabetically in tar, so when tar removes the directory a/b/c/ with all subdirectories first and then tries to remove a/b/c/d/ directory it fails with an Not found in archive in error. 并不是tac有点不需要,而是在tar中按字母顺序对文件进行排序,因此当tar首先删除包含所有子目录的目录a/b/c/ ,然后尝试删除a/b/c/d/目录时,失败错误Not found in archiveNot found in archive tac is a cheap way to fix that, so tar first removes a/b/c/d/ and then a/b/c/ . tac是修复该问题的一种廉价方法,因此tar首先删除a/b/c/d/ ,然后删除a/b/c/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM