5

The manpage of find says:

-name

Base of file name (the path with the leading directories removed)

$ find ~ -name bookmark | less

returns nothing, while

$ find ~ -name bookmarks | less
./.streamtuner/cache/bookmarks
./.config/zathura/bookmarks
./.elinks/bookmarks

has three matches.

Why does the first not have the matches of the second?

If I would like to find those files whose names contain bookmark regardless the position of bookmark in the filename, how should I use find? Thanks.

2 Answers 2

8

The pattern given to -name has to match the entire base filename. The behaviour of the -name pattern is defined as:

The primary shall evaluate as true if the basename of the current pathname matches pattern

This means it's true when the whole of the basename matches the pattern you gave. You can think of a pattern as being basically like a shell glob: you can use *, ?, and [...] patterns inside it, with the start and end of the pattern aligned with the start and end of the string.

So your command:

find ~ -name bookmarks

finds files named "bookmarks" because that is the entire filename, but:

find ~ -name bookmark

would only find files named 'bookmark', because there are no wildcard characters in the pattern.

To match files called both bookmark and bookmarks, you could use:

find ~ -name 'bookmark*'

So if you want to find

those files whose names contain bookmark regardless the position of bookmark in the filename

you can use use:

find ~ -name '*bookmark*'

to match files whose names have any number of characters, then bookmark, then any number of characters.

1
  • 4
    +1. I'd just add that the single quote around the pattern are mandatory, as otherw ise the shell itself would try to expand them, therefore sometimes (when it matches something in the current dir) changing it into something else. (And if you really want just files, add -type f after the ~ ) Jul 27, 2014 at 8:24
1

Argument of -name parameter in find command works exactly as wildcard characters in file/directory names in command line. * is any string and ? is any character.

1
  • 1
    Yes and no. If you type something like ls *.c at the command prompt, it's the shell that expands *.c and ls is given the list of such files as its arguments (e.g., ls thinks you typed ls file1.c file2.c ... file100.c). The exact same thing happens with find: find . -name *.c expands to find . -name file1.c file2.c ... file100.c and this isn't what you want: find will complain that file2.c isn't a valid option. Therefore, when using find, you must do find . -name '*.c' (or similar) so that find sees the wildcard, instead of the shell expanding it. Jul 27, 2014 at 14:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .