Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete all files that were recently created in a directory in linux?

Tags:

linux

rm

I untarred something into a directory that already contained a lot of things. I wanted to untar into a separate directory instead. Now there are too many files to distinguish between. However the files that I have untarred have been created just now (right ?) and the original files haven’t been modified for long (at least a day). Is there a way to delete just these untarred files based on their creation information ?

like image 842
AnkurVj Avatar asked Oct 01 '11 10:10

AnkurVj


3 Answers

Tar usually restores file timestamps, so filtering by time is not likely to work.

If you still have the tar file, you can use it to delete what you unpacked with something like:

tar tf file.tar --quoting-style=shell-always |xargs rm -i

The above will work in most cases, but not all (filenames that have a carriage return in them will break it), so be careful.

You could remove the directories by adding -r to that, but it's probably safer to just remove the toplevel directories manually.

like image 159
Mat Avatar answered Oct 05 '22 07:10

Mat


find . -mtime -1 -type f | xargs rm

but test first with

find . -mtime -1 -type f | xargs echo

like image 22
Artis Avatar answered Oct 05 '22 05:10

Artis


There are several different answers to this question in order of increasing complexity.

First, if this is a one off, and in this particular instance you are absolutely sure that there are no weird characters in your filenames (spaces are OK, but not tabs, newlines or other control characters, nor unicode characters) this will work:

tar -tf file.tar | egrep '^(\./)?[^/]+(/)?$' | egrep -v '^\./$' | tr '\n' '\0' | xargs -0 rm -r

All that egrepping is to skip out on all the subdirectories of the subdirectories.

Another way to do this that works with funky filenames is this:

mkdir foodir
cd foodir
tar -xf ../file.tar
for file in *; do rm -rf ../"$file"; done

That will create a directory in which your archive has been expanded, but it sounds like you wanted that already anyway. It also will not handle any files who's names start with ..

To make that method work with files that start with ., do this:

mkdir foodir
cd foodir
tar -xf ../file.tar
find . -mindepth 1 -maxdepth 1 -print0 | xargs -0 sh -c 'for file in "$@"; do rm -rf ../"$file"; done' junk

Lastly, taking from Mat's answer, you can do this and it will work for any filename and not require you to untar the directory again:

tar -tf file.tar | egrep '^(\./)?[^/]+(/)?$' | grep -v '^\./$' | tr '\n' '\0' | xargs -0 bash -c 'for fname in "$@"; do fname="$(echo -ne "$fname")"; echo -n "$fname"; echo -ne "\0"; done' junk | xargs -0 rm -r
like image 33
Omnifarious Avatar answered Oct 05 '22 05:10

Omnifarious