Search code examples
linuxrm

How delete all the empty files in linux irrespective of their directory using rm command


I have a lot of empty files in various sub directories of my Linux file system. How can I delete only empty files using the rm command?

I'm tired of deleting by going to all the directories and finding the empty files to manually delete, so I've found a combination of commands like find -size 0 -type f | rm -f. But I need to delete all the empty files in all the directories, is that possible using only the one rm command?


Solution

  • Well, rm(1) command only deletes the files whose names you pass to it on the command line. There's no code in rm(1) to allow you to filter those files, based on some condition or criteria. The old UNIX filosophy mandates here, write simple tools and couple them on pipes as neccessary to construct complex commands. In this case, find(1) is the answer... this is a tool to select files based on quite arbitrary criteria (like the one you ask for) and generate the actual file names or simply call commands based on that. On this respect

    find dir1 dir2 ... -type f -size 0 -print | xargs rm
    

    would be the solution (batching the filenames with xargs(1) command to do less fork(2) and exec(2) calls with less process fork overhead) to your problem, allowing to specify several dirs, selecting only files of size 0 and passing them to the batch command xargs(1) to erase them in groups. you can even filter the filenames based on some regular expression with

    find dir1 dir2 ... -type f -size 0 -print | grep 'someRegularExpression' | xargs rm
    

    and you'll get erased only the files that match the regular expression (and the other two predicates you expressed in find(1)) You can even get a list of the erased files with

    find dir1 dir2 ... -type f -size 0 -print | grep 'someRegularExpression' | tee erased.txt | xargs rm
    

    See find(1), grep(1), tee(1), xargs(1) and rm(1) for reference.