128

I'm on Ubuntu, and I'd like to find all files in the current directory and subdirectories whose name contains the string "John". I know that grep can match the content of the files, but I have no idea how to use it with file names.

Josh Correia
  • 3,807
  • 3
  • 33
  • 50
JJ Beck
  • 5,193
  • 7
  • 32
  • 36

4 Answers4

232

Use the find command,

find . -type f -name "*John*"
Jon
  • 9,156
  • 9
  • 56
  • 73
Rich Adams
  • 26,096
  • 4
  • 39
  • 62
  • 2
    Creating a custom bash script with `#!/bin/bash if [ -z $1 ]; then echo "Error: Specify pattern for search"; else /usr/bin/find . -type f -name "*$1*"; fi ` would let you just run `F search-string` as a perfect shortcut – Ilia Ross Jul 29 '15 at 21:13
  • @IliaRostovtsev - nice, but `[ -z "$1" ]` would be a bit better. – Joe Oct 08 '15 at 08:58
  • @Joe Ah, right. You mean in case a path has spaces? But here we only check for existence of $1 space would make $2 appear and that's it. You mean it's theoretically better, right? – Ilia Ross Oct 08 '15 at 09:34
  • @IliaRostovtsev - Actually, I was wrong. If $1 is null then the test becomes `if [ -z ]`. I thought that would be a syntax error, but it works. I can simplify some of my code from now on. – Joe Oct 08 '15 at 10:34
  • The "locate" command is orders of magnitude faster and easier to use with grep. See @thucnguyen 's answer. – DanglingPointer Jul 10 '22 at 08:29
7

The find command will take long time because it scans real files in file system.

The quickest way is using locate command, which will give result immediately:

locate "John"

If the command is not found, you need to install mlocate package and run updatedb command first to prepare the search database for the first time.

More detail here: https://medium.com/@thucnc/the-fastest-way-to-find-files-by-filename-mlocate-locate-commands-55bf40b297ab

thucnguyen
  • 1,706
  • 15
  • 14
4

This is a very simple solution using the tree command in the directory you want to search for. -f shows the full file path and | is used to pipe the output of tree to grep to find the file containing the string filename in the name.

tree -f | grep filename
caylus
  • 470
  • 4
  • 11
1

use ack its simple. just type ack <string to be searched>

Annu
  • 11
  • 3
  • It seems this will also include all _paths_ containing the search text, not just files: http://stackoverflow.com/questions/7698867/can-ack-find-files-based-on-filename-only – underscore_d Nov 18 '15 at 17:37