Tango_Chaser
Tango_Chaser

Reputation: 331

How to delete all files except directories?

I was searching unsuccessfully for a solution to delete all the files inside a working directory except for the subdirectories inside.

I found a way to delete all the files inside all the directories, but I'm looking for a way to delete only the files on the same "level" I'm on.

Upvotes: 6

Views: 18679

Answers (2)

Mateusz Piotrowski
Mateusz Piotrowski

Reputation: 9167

I think it is as easy as this:

$ rm *

when inside the working directory.

I've tested it and it worked - it deleted all files in the working directory and didn't affected any files inside any subdirectory.

Keep in mind, that it if you want to remove hidden files as well, then you need:

$ rm * .*

Upvotes: 7

IKavanagh
IKavanagh

Reputation: 6187

find . -maxdepth 1 -type f -print0 | xargs -0 rm

The find command recursively searches a directory for files and folders that match the specified expressions.

  • -maxdepth 1 will only search the current level (when used with . or the top level when a directory is used instead), effectively turning of the recursive search feature
  • -type f specifies only files, and all files

@chepner recommended an improvement on the above to simply use

find . -maxdepth 1 -type f -delete

Not sure why I didn't think of it in the first place but anyway.

Upvotes: 13

Related Questions