16

Possible Duplicate:
How to de-unzip, de-tar -xvf — de-unarchive in a messy folder?

This is a pretty annoying occurrence. Sometimes, I download an archive (tar.gz, tar.bz2, zip, rar, etc) and run tar xf [file] (or similar) in the file's directory. In rare occasions, all the files extract in the current working directory instead of a sub-directory. This can lead to hundreds of files and hundreds of patterns that can't simply be removed using a pattern matching solution.

Is there a way to get the file contents of an archive and then delete all files on that list in the current working directory?

1
  • I hate tar-bombs, so I always create a subdirectory, put the archive there and uncompress it. Just in case. An efective way is also to always redirect the verbose list of extracted files to a file, so you have a list of what to remove if this happens.
    – orion
    Commented Mar 19, 2014 at 19:22

2 Answers 2

25

You can list the content of the archive and then pass the list to rm using xargs

Example for a tarball (test it without the rm first):

tar tfz archive.tar.gz | xargs rm -rf

For .zip files, replace tar tfz archive.tar.gz with unzip -Z1 file.zip (or equivalently zipinfo -1 file.zip) (ref: https://unix.stackexchange.com/a/128304/368910)

3
  • It's definitely the smartest way to do it.
    – Deniz
    Commented Oct 9, 2015 at 9:26
  • 1
    How could it be for a zip file? Commented Feb 2, 2018 at 1:00
  • first output line is ., omit with | sed '1d' | xargs rm -rf
    – trthfgh
    Commented Apr 23, 2023 at 1:07
-1

Assuming all the files were extracted on the same date/time, you could write a one-liner and pass the regex to rm.

1
  • 2
    Could you elaborate a bit, in particular to distinguish your response from the already accepted one? Would the one-liner use find based on the mtime? And where do regexes come into this at all?
    – Kevin
    Commented Feb 14, 2012 at 4:53

Not the answer you're looking for? Browse other questions tagged .