How to Use the Unix Find Command

By Steve Claridge on 2023-09-19.

The Unix find command is a weird one for me. I've used various flavours of Linux for years but I've never really got around to using find. I think, in the past, I've been in a rush to do something on the command-line, tried to use find, it didn't work first time, so I did something else. Then, after a couple of times of find not working straight away when I needed it I confined it to the mental not-using bin and never touched it again, I thought it was about time I actually learnt how to use it.

Find allows you to find file(s) with a given name. The basic syntax is to specify a path to search from and file-mask to find.

Find a specific file in the current directory

find . -name steve.txt

As with all command-line Unix commands, you can specify the current directory with ., so in the above command I am finding in the current directory all files called steve.txt. Note a common mistake I made, and I think this is why I never knew how find worked, if you forget the -name param then find will do its default thing which is to return ALL files and directories in the given path, so

find . steve.txt

Will not just find steve.txt, it will find ALL files in .

Find all files matching a wildcard

Find all the files in /home that match the wildcard

find /home -name 'steve*'

Find this file OR find that file

find /home -name 'a.txt' -o -name 'b.txt'

The -o param is an OR operator, find this or that. Would be more useful if you were looking for wildcards, for example all PDF and Postscript files

find . -name '*.pdf' -o -name '*.ps'

Find all files and then grep for a string in them

A very common use case is looking for a string that appears in an unknown file. Here I'm looking for love in all the markdown files in all folders (including subfolfders) in the /content path

find /home/content -name '*.md' -exec grep "love" '{}' \;

Yeah, this command is a bit of a mess, you might be better off using the far easier grep alternative, the downside with grep is that you can narrow down the filename match as find would, this recursive grep will search all files

grep -r love /home/content

Case insensitive filename match

The `-iname' flag doesn't care about filename case

find /home -iname 'SteVe*'