2

Possible Duplicate:
How to delete all files in a directory except some?

I often face this problem. I have a set of files in a folder and would like to delete all of them except a few.

For example: I have files named according to the date of creation (like 11-1-11.tar, 10-1-11.tar and so on). Now I would like to delete files like 10-1-11, 9-1-11 and so on but not some other files. Basically I would like to enforce what all should be deleted and what should be retained. How would I do this?

0

4 Answers 4

3

If this is BASH, you could consider using extended globbing. To enable:

shopt -s extglob

(Put that in your .bashrc if you want, or just turn it on when you need it.)

And then, e.g., to delete all the files except filename1 and filename2

rm !(filename1|filename2)

You can also use wildcards like * in there too.

Or you could delete all those matching a pattern:

rm +([0-9])-+([0-9])-+([0-9]).tar

would delete all #-#-#.tar files (where the numbers have 1 or more digits).

It's unclear whether this would meet your needs or not. More details here.

2

If the filename corresponds with the creation date of the file, it may just be easier to delete files older than a certain day.

This is easily achieved with the find command:

find /home/john/files -type f -mtime +30 -delete

this would delete files under /home/john/files which have a modification date longer than 30 days ago.

0

you may also be able to do what you want with tmpwatch

http://linux.about.com/library/cmd/blcmdl8_tmpwatch.htm

tmpwatch -m 24 /path/to/dir

will delete all files in the dir older than one day since last used (-m).

0

I think, you can use several UNIX command in one pipe and it will solve your problem. One of possible solution is using find | grep | xargs rm -rf. For example:

$ find /path/to/directory/tree -type f | grep -v -E -f /path/to/exclude/file | xargs rm -rf

For excluding some files just put their names into file /path/to/exclude/file. For example:

very_useful_file.tar.gz
very_important_file.jpg

For preventing incorrect wiping of important files I suggest make backup copy of all files. It's also useful using xargs with -p option, which ...Prompt the user about whether to run each command line and read a line from the terminal.

It's possible to use find tool without grep/xargs. It will be something like that: find /path/to/tree -type f ! -name "exlude_pattern"

Before using these commands read manual pages carefully for find/grep/xargs! They can be very dangerous:).

1
  • You might also want to carefully consider whether you want to use -r (recursive) (and perhaps -f (force)) when you're feeding filenames to xargs for rm. Jan 12, 2011 at 2:22