100 Useful Command-Line Utilities

by Oliver; 2014

55. find

find is for finding files or folders in your directory tree. You can also use it to list the paths of all subdirectories and files of a directory. To find files, you can use the simple syntax:
find /some/directory -name "myfile"
For instance, to find all files with the extension .html in the current directory or any of its sub-directories:
$ find ./ -name "*.html"
The flag -iname makes the command case insensitive:
$ find /my/dir -iname "*alex*"
This would find any file or directory containing ALEX, Alex, alex, and so on in /my/dir and its children.

To see the path of every child file and directory from the cwd on down, simply type:
$ find
This could come into play, for example, when you're trying to clean up your folders. In addition to how big a folder is (remember du -sh), you might also want to know if the folder has a gazillion files in it. Try:
$ find mydirectory | wc -l
Say you want to refine this and ask how many files are in each of mydirectory's child directories. Then use:
$ for i in mydirectory/*; do echo "***"$i; find $i | wc -l; done
All this is to say, find is one of the best tools to print out file paths, irrespective of whether you're looking for a file.

find works particularly well in combination with xargs. For example, delete any files called tmp.txt in mydirectory:
$ find mydirectory -name "tmp.txt" | xargs rm
You could also, of course, do this in a plain loop:
$ for i in $( find mydirectory -name "tmp.txt" ); do echo $i; rm $i; done
Zip any file with the extension .txt in mydirectory:
$ find mydirectory -name "*.txt" | xargs gzip
Ditto with a loop:
$ for i in $( find mydirectory -name "*.txt" ); do echo $i; gzip $i; done

<PREV   NEXT>