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
  • 55,929
  • 26
  • 146
  • 227
Daichi42
  • 23
  • 3

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
  • 234,489
  • 66
  • 447
  • 667
John
  • 16,759
  • 1
  • 34
  • 43
  • 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