Find Command (Linux)

I often use the Find command to look for filenames / directories  which match some substring.

Note: Unlike grep, Find only looks at filenames. It doesn’t look at the contents of the files themselves.

Tips:

[1]  Find can be quite tricky when it comes to looking at substrings. Unlike grep, it doesnt look at substrings  unless it is specified precisely using wildcards.

e.g.  There is a difference between the two:

  • find . -name ‘my*’
    • This searches in the current directory (represented by the dot character) and below it, for files and directories with names starting with my
  • find . -name ‘*my*’
    • This searches in the current directory (represented by the dot character) and below it, for files and directories with names containing substring my.

[2]  Find can be especially useful with the -exec option.  Another possibility is to use xargs with find.

  • However, I have come to the conclusion that its extremely risky to use either of these two  with the find command   .  Read more here.
  • Almost always there will be other ways to achieve the same thing. Do explore those before using  the -exec option  or before you use it with the xargs  command.

[3]  ignore case. By default find is case sensitive. However, recent versions of GNU find have an -iname flag, for case-insensitive name searches

$ find . -iname ‘*udo*’ -type d
./Scope.UDOs
./Scope.UDOs/UDO_Training

 

Examples:

[1] From current directory

find . -name ‘my*’

This searches in the current directory (represented by the dot character) and below it, for files and directories with names starting with my. The quotes avoid the shell expansion — without them the shell would replace my* with the list of files whose names begin with my in the current directory. In newer versions of the program, the directory may be omitted, and it will imply the current directory.

 

[2] Files only

find . -name ‘my*’ -type f

This limits the results of the above search to only regular files, therefore excluding directories, special files, pipes, symbolic links, etc. my* is enclosed in single quotes (apostrophes) as otherwise the shell would replace it with the list of files in the current directory starting with my……

 

 

[3] Search several directories

find local /tmp -name mydir -type d -print

This searches for directories named mydir in the local subdirectory of the current working directory and the /tmp directory.

 

References:

 

 

 

 

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s