Remove only files in directory on linux NOT directories

AndrewC picture AndrewC · Oct 10, 2011 · Viewed 93.7k times · Source

What delete command can be run to remove only files in given directory

  • NOT directories
  • NOT sub-directories
  • NOT files in these sub-directories.

Some files don't have extensions so rm *.* wont work...

There are thousands of files in this folder.

Any advice?

Answer

chown picture chown · Oct 10, 2011

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.