Useful ways to use the Linux “find” command


In my Linux life, I find myself trying to search for files quite frequently. All distributions comes with a very handy command called ‘locate’ which helps you search for the file. What it does is Linux keeps an index and database of all the files and locations and this command would search inside that database to try to look for the file you want.

However, what you might find out is you will need to keep that database up to date before you can search anything new. In order to keep that database updated you have to run a command called ‘updatedb’ and it will churn away indexing your files. The down side with this is that it often takes a long time for it to come back (depending on how big your file system is). This is when the good old ‘find’ command comes to use.

The find command is pretty simple to use. Here’s the syntax:

find path -name 'filename' path arguments

Here are some examples

find . -name 'foo'

What this command does is it searches your current directory for the filename that contains the word foo.

Other varations include

find / -maxdepth 2 -name 'foo'

This command searchs for foo from / directly with a maximum of 2 directories deep.

After all that what I wanted to remind myself was this command

find . -maxdepth 1 | sed 's/\.\///' | xargs -i chown -R {}.{} {}/

AHA! mumbo jumbo. What this command does is it searches the local directory, prints out the filenames and then strips out the ./ and then changes the ownership of the files(directories I should say) in question to the name itself?

So you might think, why would I do that? Well today I came across a system that had some screwed up home directories where ownership of directories did not belong to who they are suppose to. This command fixes all that, find find the directory name and changing the ownership back to it’s real owner (which happens to be the name of the directory)

This command combines a series of linux command parsing, but what I want to make note is the ‘xargs’ command. This neat little command feeds from stdin and allows you to form a command which takes that input as an argument. In this very special case, it’s especially useful in combo with the find command as it can feed input from the results of the search into a powerful chain command. One thing to make note is that the find command itself comes with ‘-exec’ option which does the same thing, however in my case I had piped it once so I couldn’t use the -exec command to do it.

Well to sum up, I’ve used this command many times and I think it deserves to stay in my memory for future use!

Related Posts with Thumbnails

About the Author

Alfred Tong
Author and owner of this blog. A Networking enthusiast, full time networking and systems Engineer. Generally curious about all things IT.Certifications: GIAC GSEC, CCNP-S, CCNP, CCSP, CCDP, CCNA, RHCE, JNCIA - FWV