Remove only files in directory on linux NOT directories

Since this is high on google search, the simplest answer is:

rm $directoryPath/*

where $directoryPath is the directory you want to empty. Credits should go to cbm3384 (that for some reason has gotten negative votes for this answer, why?)

If you do not want to confirm:

rm -f $directoryPath/*

If you don't believe try man rm or

mkdir -p 1/2/3; echo 'hello1' > 1/hello1.txt; echo 'hello2' > 1/2/hello2.txt;echo 'hello3' > 1/2/3/hello3.txt
rm 1/2/*

The above creates a directory structure, that has 'helloX.txt' in each folder (X is the directory level). rm 1/2/* deletes hello2.txt and leaves the other structure intact.

Also rm */*/* deletes only hello2.txt. It is the only that matches the pattern.

Just an example of a Makefile that cleans cakephp tmp-directory and leaves the directory structure intact:

clean:
    -rm -f tmp/*
    -rm -f tmp/*/*
    -rm -f tmp/*/*/*
    -rm -f tmp/*/*/*/*

Minus in front of the rm means "do not halt on errors" (unremoved directory returns an error). If you want some level to be saved, just remove that line, e.g. second rm line removes logs.

Let me know if you have a system that does something else (BSD?).

EDIT: I tested this on ubuntu 12.04, osx lion and sourceforge.net shell. All behave like the explanation above.


find PATH -maxdepth 1 -type f -delete

BUT this won't prompt you for confirmation or output what it just deleted. Therefore best to run it without the -delete action first and check that they're the correct files.


You can use find with -type f for files only and -maxdepth 1 so find won't search for files in sub-directories of /path/to/directory. rm -i will prompt you on each delete so you can confirm or deny the delete. If you dont care about being asked for confirmation of each delete, change it to rm -fv (-f for force the delete). The -v flag makes it so that with each delete, a message is printed saying what file was just deleted.

find /path/to/directory -maxdepth 1 -type f -exec rm -iv {} \;

This should meet the criteria:

NOT directories
NOT subdirectories
NOT files in these subdirectories.

Tags:

Linux

Rm