Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 959
Tango_Chaser Avatar asked Aug 12 '15 12:08

Tango_Chaser


People also ask

How do I delete all files except one file?

Using rm command Here is the command to delete all files in your folder except the one with filename data. txt. Replace it with the filename of your choice. Here is the command to delete all files in your folder, except files data.

How do I delete all folders except one directory in Linux?

Details: ls myfolder/ lists all folders and files inside myfolder/ directory. grep -v "test2" matches everything except "test2" xargs rm -r pipes the output from previous command to rm -r command.

How do I select all except one folder?

Select multiple files or folders that are not grouped together. Click the first file or folder, and then press and hold the Ctrl key. While holding Ctrl , click each of the other files or folders you want to select.

How do you delete all files except the latest three in a folder windows?

xargs rm -r says to delete any file output from the tail . The -r means to recursively delete files, so if it encounters a directory, it will delete everything in that directory, then delete the directory itself.


2 Answers

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.

like image 101
IKavanagh Avatar answered Sep 30 '22 07:09

IKavanagh


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 * .*
like image 32
Mateusz Piotrowski Avatar answered Sep 30 '22 06:09

Mateusz Piotrowski