2

This seemed great: find . ! -name *custom.conf -delete

But it does not work if I don't have any custom.conf :(

I am thinking about:

  • split into 2 folders
  • use a regex in the find command

disclaimer: this is my first question here, I thought it could have been better to add a comment to https://unix.stackexchange.com/a/247973/247207 but I don't have the required reputation to post a comment

1 Answers1

1

The issue here is that the filename globbing pattern on the command line will be expanded by the shell (if it matches any names in the current directory) before the utility is invoked.

This means that the actual command being executed may be something like

find . ! -name thing1-custom.conf thing2-custom.conf thing3-custom.conf -delete

You can see this if you enable tracing with set -x on the command line before invoking the command. Use set +x to later turn off tracing.

Your command also ought to have given you one of the error messages unknown option or paths must precede expression depending on your implementation of the find utility.

The correct thing to do here is to quote the pattern from the shell, as Michael Homer pointed out in comments (he says to escape the *, but quoting the whole pattern is IMHO nicer looking and has the same effect):

find . ! -name '*custom.conf' -delete

This way, the pattern is handed over to find as is, and the utility will do its own matching against all the names in the current directory.

I would also add -type f to that so that we're sure we'll only act on regular files:

find . -type f ! -name '*custom.conf' -delete
Kusalananda
  • 333,661