When working with filesystem in Linux, might be need to find and remove empty files and directories. This tutorial demonstrates how to do that in Linux.
Create few directories and files for testing:
mkdir -p docs/dir_1 docs/dir_2 docs/dir_2/dir_3
touch docs/test_1.txt
touch docs/dir_2/test_2.txt
echo "Hello world" > docs/dir_2/test_3.txt
We created 2 empty directories dir_1 and dir_3 and 2 empty files test_1.txt and test_2.txt.
Empty files and directories can be found and removed by using find command with -empty and -delete option.
In order to find and remove empty files in given directory (docs directory in our case), use the following command:
find docs -type f -empty -delete
To find and remove empty directories, for -type option use d value instead of f.
find docs -type d -empty -delete
Leave a Comment
Cancel reply