I just untar'd an archive that produced a mess of files into my tidy directory. For example:
user@comp:~/tidy$ tar xvf myarchive.tar
file1
file2
dir1/
dir1/file1
dir1/subdir1/
dir1/subdir1/file1
dir2/
dir2/file1
...
I was expecting that the tar file would have been organized in a single folder (i.e., myarchive/
), but it wasn't! Now I have some 190 files and directories that have digitally barfed in what was an organized directory. These untar'd files need to be cleaned up.
Is there any way to "undo" this and delete the files and directories that were extracted from this archive?
Thanks for the excellent answers below. In summary, here is what works with two steps (1) delete files, and (2) delete empty directory structure in reverse packing order (to delete outer directories first):
tar tf myarchive.tar | xargs -d'\n' rm
tar tf myarchive.tar | tac | xargs -d'\n' rmdir
And safer yet, to preview a dry-run of the commands by appending echo
after xargs
.
Best Answer
will list the contents line by line.
This can be piped to
xargs
directly, but beware: do the deletion very carefully. You don't want to justrm -r
everything thattar tf
tells you, since it might include directories that were not empty before unpacking!You could do
to first remove all files that were in the archive, and then the directories that are left empty.
sort -r
(glennjackman suggestedtac
instead ofsort -r
in the comments to the accepted answer, which also works sincetar
's output is regular enough) is needed to delete the deepest directories first; otherwise a case wheredir1
contains a single empty directorydir2
will leavedir1
after thermdir
pass, since it was not empty beforedir2
was removed.This will generate a lot of
and
Shut this up with
2>/dev/null
if it annoys you, but I'd prefer to keep as much information on the process as possible.And don't do it until you are sure that you match the right files. And perhaps try
rm -i
to confirm everything. And have backups, eat your breakfast, brush your teeth, etc.