I would like to remove all files from a directory /data which includes 8 other sub directories.
Is there a command which will recursively clear all subdirectories but not remove the actual folders?
I would like to remove all files from a directory /data which includes 8 other sub directories.
Is there a command which will recursively clear all subdirectories but not remove the actual folders?
The following would delete any non-directory files, like regular files, symbolic links, named pipes, sockets etc., in or under the /data
directory:
find /data ! -type d -delete
For implementations of find
that does not have the non-standard predicate -delete
, use -exec rm -f {} +
in its place:
find /data ! -type d -exec rm -f {} +
This would find all non-directory files in or under /data
and would execute rm -f
on as large batches of these as possible.
Use find command
find /data -type f -exec rm -rf {} \;
will delete only files due to the type selection type f for files.
You can use the find
command for this.
To create a test case to reproduce your description, let me do this:
1. cd /tmp
2. mkdir -p testing/{a,b,c}
3. cd testing/
4. touch {a,b,c}/{1,2,3}
To verify there are multiple directories each containing multiple files:
$ find -type f
./c/3
./c/2
./c/1
./b/3
./b/2
./b/1
./a/3
./a/2
./a/1
You can now use find
again to delete whatever it finds:
find -type f -delete
If you now run find -type f
again it will not return any results, because the files are gone, but you can see that the directories still exist:
$ ls
a b c
The find
command is very powerful. You can discover more about it using man find
.
-delete
is a GNUism :)
Commented
Nov 11, 2018 at 22:20
-delete
is from FreeBSD (1996). Only added to GNU find
in 4.2.3 (2004) (and to NetBSD find in 2007)
Commented
Nov 11, 2018 at 22:43
-delete
was added in January 2017 to OpenBSD find
, if you want to be complete...