Search code examples
bashdirectorydelete-filesubdirectory

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.


Solution

  • 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.