loading...

How to Delete All Files Except Diretories

serhatteker profile image Serhat Teker Originally published at tech.serhatteker.com on ・2 min read

Case

I want to delete all files inside the $ROOT of working directory except directories themselves.

I faced this challange when I started a new GoHugo project and wanted to iterate/play around typical exampleSite content.

Example content for a new GoHugo project:

user@host:~$ ls -la
total 52K
-rw-r--r-- 1 user user 1.3K Jul  9 17:44 .
-rw-r--r-- 1 user user 1.3K Jul  9 17:44 ..
-rw-r--r-- 1 user user 1.3K Jul  9 17:44 config.toml
drwxr-xr-x 3 user user 4.0K Jul  9 17:44 content
drwxr-xr-x 9 user user 4.0K Jul  9 17:44 .git
-rw-r--r-- 1 user user   20 Jul  9 17:44 .gitignore
-rw-r--r-- 1 user user  160 Jul  9 17:44 .gitmodules
drwxr-xr-x 4 user user 4.0K Jul  9 17:44 layouts
-rw-r--r-- 1 user user   79 Jul  9 17:44 Makefile
drwxr-xr-x 3 user user 4.0K Jul  9 17:44 public
-rw-r--r-- 1 user user   20 Jul  9 17:44 README.md
drwxr-xr-x 3 user user 4.0K Jul  9 17:44 resources
-rw-r--r-- 1 user user 2.2K Jul  9 17:44 Session.vim
drwxr-xr-x 3 user user 4.0K Jul  9 17:44 static
drwxr-xr-x 3 user user 4.0K Jul  9 17:44 themes

Solution

Finding files:

$ find . -type f

To make this only for current dir —$ROOT, add -maxdepth flag:

$ find . -maxdepth 1 -type f

Final solution would be:

$ find . -maxdepth 1 -type f -delete

Warning

Make sure you selected right files before using -delete flag. So check more than one the output of find.

Bonus Tip

To exclude a dir from your find use, -prune flag. For instance in order to exclude .git dir from our searches use one of the below commands:

$ find . -type d -name .git -prune -o -type f -print
$ find . -path ./.git -prune -o -print

All done!

Posted on by:

serhatteker profile

Serhat Teker

@serhatteker

Uomo Universale | Software Engineer | Entrepreneur | builds systems | py:js:go |

Discussion

markdown guide