Using ‘find’

Finding files

To find all ‘.c’ source code files in the current directory (and sub directories):

$ find -type f -iname '*.c'
./decBasic.c
./decCommon.c
./decContext.c
:
:
:
./example8.c

To find find all the ‘.c’ and ‘.h’ source code files you can combine multiple search terms:

$ find . -type f -iname ‘*.c’ -o -iname ‘*.h’
./decBasic.c
./decCommon.c
./decContext.c
./decContext.h
:
:
:
./example8.c

Finding all the files that match multiple different file extensions is also possible using a regular expression though I find this method rather harder to remember!

$ find -type f -iregex '.*\.\(c\|h\)'
./decBasic.c
./decCommon.c
./decContext.c
./decContext.h
:
:
:
./example8.c

Count directories and files in a folder

To count how many files folders and symbolic links are in a particular directory (including sub folders).

$ for _type in files directories links; do \
>   echo "$(find . -type ${_type:0:1} | wc -l)" $_type; \
> done
47447 files
5499 directories
7 links
$

This command searches the current folder for each of the types of file specified in the ‘for’ loop, and counts the number of lines of output for each to produce a summary giving the total number of files, folders and links.

If you just want to know what is in the current folder and don’t want to count any files, folders or links in any sub-folders you can use limit the search to just the current folder and exclude hidden files.

$ for _type in files directories links; do \
>   echo "$(find . -maxdepth 1 -type ${_type:0:1} ! -path "*/\.*" \
>   | wc -l)" $_type; \
> done 2> /dev/null
287 files
9 directories
0 links
$

Generate checksums

The following command find all the matching files in the current folder (excluding hidden files) and then generates a checksum for each one, saving the output in a file.

$ find . -iregex ".*\.\(tar\|gz\)" -type f ! -path "*/\.*" \
> -exec md5sum {} \; |tee checksum.md5

Find large files

The following commands both use use ‘-size’ to find any file larger than a certain size, but the first one also shows how ‘find’ can be used to run more then one command for each matching file.

$ find . -size +10M -exec printf "{} " \; -exec stat -c %s {} \;

The second command is less ‘interesting’ but does the same thing more efficiently as ‘stat’ can be used to print the filename as well as the file size.

$ find . -size +10M -exec stat -c "%n %s" {} \;