5

On Ubuntu 14.04, 64 bit, I have set /lib/modules/4.2.0-27-generic/kernel/drivers to be my current directory. I intend to search all files having net present as a sub-string. If I search with a regex of *net*, only the ./net directory is returned as the search result. However, if I specify exact file name, then only it lists out the relevant file (Useless because not always I know the exact file name to cross check).

$ find . -name *net* 
./net
$ find . -name *usbnet* 
./net/usb/usbnet.ko
$ pwd
/lib/modules/4.2.0-27-generic/kernel/drivers

What mistake am I making?

sherlock
  • 626
  • 1
    it's a matter of shell expansion see here : http://stackoverflow.com/questions/36375819/wildcards-and-double-quotes-with-find-name-command – netmonk Jun 29 '16 at 07:06

1 Answers1

13

Because when you use just *net* (without any quoting or escaping), it will be expanded by the shell as the (existing) net file/directory in the current directory before the find command run. So the command becomes:

find . -name net

As you can see it is just matching net, so usbnet.ko will not be matched.

Also note that, without quoting and escaping, if the pattern does not match (and nullglob and failglob options are disabled), it is treated as is. So for example, for find . -name *net*, if no file name contains net in current directory the pattern find gets is *net*.


So to solve the problem, you need to avoid the shell globbing, to do so you can use quoting or escaping the glob patterns:

find . -name '*net*' 
find . -name "*net*" 
find . -name \*net\* 
heemayl
  • 56,300
  • What I didn't understand is why bash strips off wildcards(*) during expansion (if used without quoting or escaping). – sherlock Jun 29 '16 at 07:10
  • 1
    It is not stripping them, it is using them to match. – matzeri Jun 29 '16 at 07:13
  • 1
    @Holmes.Sherlock bash does not strip off wildcards, do ls *net* and you will see you have only one file named net n that directory. If there are other files e.g. foonetbar, spamnet, then *net* would match them too.. – heemayl Jun 29 '16 at 07:13
  • 1
    A lot of users imagine that the globbing is done in ls. To see what the shell is doing, and break this illusion, do echo *net*. – ctrl-alt-delor Jun 29 '16 at 07:37
  • 2
    and the other point is that when a pattern does not match, then bash does not remove any of the wildcard characters, and find gets the argument *usbnet* with asterisks – glenn jackman Jun 29 '16 at 10:46
  • @glennjackman Missed that..edited.. – heemayl Jun 29 '16 at 14:25
  • What's the difference between find . -name '*net*' and find . -name *net*? – pmor Nov 24 '23 at 10:48