How to remove all empty plain text files using GNU utils ?
I was working on a project that automate some data analysis and statistics. In that script I rely heavily on creating and modifying plain text files. After running that script for hours I got hundreds of plain-text files. So, I need to remove all empty ones.
Here are the ways I used to remove all empty text files.
List all empty text files ๐
I run this code to get all empty files, to make sure it grabs empty files.
find . -type f -name "*.txt" -size 0
Remove the empty files ๐
Then I re-run the command but append -delete to it, to remove all files it grabs.
find . -type f -name "*.txt" -size 0 -delete
Here is a break down for the command:
find .: This starts thefindcommand and tells it to search in the current directory (.) and all its subdirectories.-type f: This option limits the search to regular files (not directories, symbolic links, etc.).-name "*.txt": This further filters the search to only files ending with the.txtextension. If you want to delete all empty files, regardless of extension, omit this part.-size 0: This option selects files with a size of 0 bytes, which are empty files.-delete: This option deletes the files that match the criteria. It’s often a good idea to first run the command without-deleteto see which files will be affected (and that is my cautious strategy always).
Not GNU find ๐
This solution relies on GNU find, which is the standard on most Linux systems. On other Unix-like systems, the -delete option may not be available. If it is not available, you can use the -exec rm {} \; option instead:
find . -type f -name "*.txt" -size 0 -exec rm {} \;
This alternative approach executes the rm (remove) command for each found file.
I hope you enjoyed reading this post as much as I enjoyed writing it. If you know a person who can benefit from this information, send them a link of this post. If you want to get notified about new posts, follow me on YouTube , Twitter (x) , LinkedIn , and GitHub .