Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting subdirectories and files in a given directory

I want to delete all subdirectories and files from a directory, but not the directory itself. For examnple, if I pass "Sample" directory in a variable, and "Sample" directory contains three subdirectories and 3 files, I want to delete all that 3 directories and 3 files. In practice, the "Sample" directory can contain many subdirectories and files.

like image 698
Shaggy Avatar asked Jan 18 '23 04:01

Shaggy


1 Answers

ETA: This is actually in perlfaq5: How do I delete a directory tree?

Use File::Path, core module.

perl -MFile::Path=remove_tree -we 
    'remove_tree("Sample",{keep_root=>1}) or die $!'

The keep_root option will cause remove_tree to keep the top directory:

keep_root => $bool

When set to a true value, will cause all files and subdirectories to be removed, except the initially specified directories. This comes in handy when cleaning out an application's scratch directory.

like image 121
TLP Avatar answered Jan 25 '23 11:01

TLP