26
Aug

Remove a File / Directory from a Tarball Without Extracting First

If you have an extra folder or file within a tarball (.tar) file, you can remove it without extracting the entire tarball first. This can be really handy when you have a massive file that you don’t want to spend a lot of time extracting and re-archiving. Open up a terminal shell and follow along with the example below.

We’ll first see what’s in the compressed tarball named sandbox.tar.gz by using the --list option of tar:

thelinuxdaily$ tar --list --file=sandbox.tar.gz
sandbox/
sandbox/delete_me/
sandbox/delete_me/hello.txt
sandbox/hello.txt
sandbox/hello2.txt
sandbox/hello3.txt
sandbox/save_me/
sandbox/save_me/hello.txt

Let’s try to delete the folder called sandbox/delete_me from the compressed tarball:

thelinuxdaily$ tar --delete --file=sandbox.tar.gz sandbox/delete_me
tar: Cannot update compressed archives
tar: Error is not recoverable: exiting now

See what happened? That means we need to uncompress it. In this case, it’s a .gz compression type, so we’ll use gunzip (if you were using bz2, you’d use bunzip2:

thelinuxdaily$ gunzip sandbox.tar.gz

Let’s try to delete the folder sandbox/delete_me again:

thelinuxdaily$ tar --delete --file=sandbox.tar sandbox/delete_me

We didn’t get an error message, so that’s good. Let’s see if it’s gone by using --list again:

thelinuxdaily$ tar --list --file=sandbox.tar
sandbox/
sandbox/hello.txt
sandbox/hello2.txt
sandbox/hello3.txt
sandbox/save_me/
sandbox/save_me/hello.txt
thelinuxdaily$ gzip sandbox.tar

Excellent! That’s what we needed to see. If you have any other tips, feel free to use the comments below.

Feel free to donate if this post prevented any headaches! Another way to show your appreciation is to take a gander at these relative ads that you may be interested in:


There's 2 Comments So Far

  • Krausdogs
    August 16th, 2013 at 3:22 pm

    Haven’t tried doing this in a while, though the last time did not work and basically corrupted my tar file. I assumed this was because a .tar file is a ‘tape archived file’ which contains the uncompressed byte streams of the files it contains. My understanding was that this format made it very difficult to add to or remove things from a tar file.
    Maybe times have changed and things improved (also hoping this is not tied what version of Linux one is using).

    Now I just tried your instructions and was able to add files (not able to add a folder yet), then gzip’d and gunzip’d the file, and then remove the files I had added previously. This is looking promising. More testing will enhance my faith in these processes. I will let you know if I come across any issues in the near future.
    Thanks, this exercise was helpful.

Who Linked To This Post?

  1. Securitron GNU/Linux blog. Linux tips and support for Ubuntu and Fedora alike. Posting about my Linux experiences.

Share your thoughts, leave a comment!