1

I'm having some trouble while searching files with find command and the way it handles the search.

Let's say I'm currently in the directory /tmp and the directory contains the files: backup-20151219.zip, backup-20151220.zip, backup-20151221.zip.

Then my search command is:

[root@server tmp]# find /tmp -type f -mtime +2 -name backup* -exec rm -f {} \;

And I get the following:

find: paths must precede expression: backup-20151219.zip
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]

That's because it matched the backup* regex and used it as the search pattern instead of using it to filter results. That I know.

If I change to another directory which does not contain files beginning with backup*, it shows the expected results.

So, I wanted to know if there is a way to search files using wildcards while being in a directory that may contain matches and show them as results.

Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232

1 Answers1

5

In short - yes there is way. You simply have to escape the wildcard characters somehow. There are multiple ways to do this, the method I use most often is to escape the particular wildcards:

find . -name backup\* -print

Or, simply quote the pattern:

find . -name "backup*" -print

Other ways will work just as well - the main point is to somehow prevent the shell from seeing the wild card as a glob expression.

terdon
  • 242,166
John
  • 17,011
  • 1
    You might want to note why the unescaped * breaks things. The shell expands backup* to any files it finds in the current directory. Then find will "see" a "bare" filename ... find /tmp -name backup1 backup2 .... It's the backup2 which find complains about. Feel free to copy/paste this back into your answer. – Otheus Dec 21 '15 at 15:08
  • 1
    @Otheus: Well, the OP said that he already understood that. – Scott - Слава Україні Dec 21 '15 at 21:52
  • I can't believe it was as simple as just quoting the search expression... Thanks a lot! – Daichi42 Dec 22 '15 at 17:04
  • @Scott indeed he did. In THAT case you might want to add that the reason it works outside the /tmp directory is because of a particular option in bash which will treat backup* as a literal if there are no matching files. When the option is set differently, backup* will expand to the empty string. – Otheus Dec 22 '15 at 22:08