Removing files called X and containing Y in Bash

I recently had cause to remove all files with a particular name and containing a particular string from some production servers. Below is the Gist I used to do it. The first part of the script is some basic validations, but line 43 is where the main work is done. We first `find` all files named `example.html`, we then pass those to `grep` to check for the string, and, if the string is found, finally we pass the file paths to `rm` to verbosely (so we have a record of what was removed) remove them.

While checking this script, my colleague Sean introduced me to Shell Check, which in turn pointed to two ways I could tighten the original script:

Firstly, and most simply, I wasn’t quoting the `$PATH_TO_INSTALLS` on line 43 in the script; this could have caused issues if my file path contained spaces. This was fixed pretty easily.

Secondly, and along similar lines, I was not aware that `xargs` might interpret said spaces in unexpected and inglorious ways. To fix this, I’ve added `-print0` to the `find` command and `-0` to my `xargs` commands.

One thought on “Removing files called X and containing Y in Bash”

  1. You can use -exec with find, so you don’t need to pipe into the first xargs;
    find "$PATH" -name example.html -exec grep -lIZ "Genericons" {} \; | xargs -0 rm -fv --
    Not tested it, or spent much time, but should work :)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.