Given that I:

  • have a directory that contains over 1000 files
  • have a gzip'ed tar file that contains a subset of those files (x.tgz)

What is the single command line (if it is possible) that will read the gzip'ed tar file's contents and removes all of the files from the directory that are contained within the tar file?


You would need to be at the directory from which the tar file was created, for instance $HOME. Then if you had a tgz of your Documents directory located safely in /backup/Documents.tgz you would do this:

$ for file in $(tar -tzf /backup/Documents.tgz); do \
      [[ -f $file ]] && rm $file || echo "$file does not exist"; done

If you want to also delete directories you would use rm -fr $file.

  • This does not work if you have symlinks in the archive. – schily Sep 4 '15 at 13:12

May be something like this will help you

rm -rf `find . -name '*.tgz' -exec tar -tzf '{}' \;`

not sure how it will work with so many files.

$ tar -tzf x.tgz  |grep -v '/$' | xargs -n1 -d '\n' echo rm

Remove the echo if it looks good.


  • tar -tzf x.tgz -- list the contents
  • grep -v '/$' -- skip directories
  • xargs -n1 -d '\n' echo rm -- for each one (-n1) line (-d '\n') of input, run echo rm
  • As mentioned in the other answer: this does not work if there are symlinks in the archive. – schily Sep 4 '15 at 13:13

As tar (even in non-verbose mode) lists symlinks and hardlinks in the tar t output, you cannot use tar t to get the list if files. Better use:

star -t -tpath < archive.tar > file-list.txt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.