All commands tested on Mac OS Monterey / Sep 12, 2023

How to delete a file from an existing tar archive

Delete a file from an existing tar archive.

You can use this short tar command.

              
                  tar --exclude my-file.txt -cvf --file temp.tar @files.tar && rm files.tar && mv temp.tar files.tar
              
          

Or this more verbose tar command.

              
                  tar --exclude my-file.txt --create --verbose --file temp.tar @files.tar && rm files.tar && mv temp.tar files.tar
              
          

What's heppening here?

We want to remove the file my-file.txt from the tar archive files.tar. Whereas some tar implementations support the --delete option, for those that don't (Mac OS, for sure), here's how this works:

  1. Create a new tar archive temp.tar with the contents of files.tar, excluding my-file.txt.
  2. Remove the original tar archive.
  3. Rename the new temp archive to the name of the original.

There may be more elegant approaches to achieve this. However, this solution does work and allows you to get on with your life.

Note: Because we're deleting the original tar file, do ensure to take a backup before you do this.


Load WordPress Sites in as fast as 37ms!

Options explained

  1. --exclude tells tar not to process files or directories that match the specified pattern
  2. u or --update tells tar to add to the archive if the modification time is newer than in the archive
  3. v or --verbosetells tar to produce verbose output
  4. f or --filetells tar that the next parameter will be the tar file to create, extract, append to, list, etc.

More commands to update tar archives