1

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?

4

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.

0

Use find command

find /data -type f -exec rm -rf {} \; 

will delete only files due to the type selection type f for files.

  • 2
    No need for -r if you're removing files... – Jeff Schaller Nov 11 '18 at 22:11
0

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.

  • 1
    The question isn't yet tagged Linux, so I'll just note that -delete is a gnu extension to find. – Jeff Schaller Nov 11 '18 at 22:13
  • @JeffSchaller Ah, noted. Thanks for that, it wasn't on my radar that -delete is a GNUism :) – cryptarch Nov 11 '18 at 22:20
  • 1
    @JeffSchaller, -delete is from FreeBSD (1996). Only added to GNU find in 4.2.3 (2004) (and to NetBSD find in 2007) – Stéphane Chazelas Nov 11 '18 at 22:43
  • 1
    @StéphaneChazelas -delete was added in January 2017 to OpenBSD find, if you want to be complete... – Kusalananda Nov 11 '18 at 22:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.