I have blogged before that knowledge of command-line tools is essential to take the next step in programming productivity. I think it would be useful to provide simple tutorials for these powerful tools, starting with find. I hope you agree, and would appreciate your feedback via the contact page or in the comments.
Tutorial
If you’re on Windows, I would recommend installing Cygwin to bring the power of a real shell to your OS. Let us start with a simple example and build upon it:
view plaincopy to clipboardprint?
1.
find . -name "*.css"
find . -name "*.css"
This will list all CSS files (and directories ending with ".css") under the current directory (represented by "."). We only want to match files so we’ll go ahead and change it to this:
view plaincopy to clipboardprint?
1.
find . -type f -name "*.css"
find . -type f -name "*.css"
Now we will only match CSS files. Nothing special? Fine, I see how it is. Let’s find all CSS files that do something with your HTML ID #content next:
view plaincopy to clipboardprint?
1.
find . -name "*.css" -exec grep -l "#content" {} \;
find . -name "*.css" -exec grep -l "#content" {} \;
Here we combine find with grep (covered in detail later) using the
We’re starting to get productive now, so let’s keep going. Suppose now we want to change every reference to the color #FF0000 (red) to #00FF00 (green). Normally you would have to have your editor search and replace them, if it even has that capability. Even then it’s slow, this statement is fast:
view plaincopy to clipboardprint?
1.
find . -name "*.css" -exec sed -ier 's/#(FF0000|F00)\b/#0F0/' {} \;
find . -name "*.css" -exec sed -ier 's/#(FF0000|F00)\b/#0F0/' {} \;
Gasp! Wait a minute, I just searched for both ways to specify red and replaced it with green in my CSS!! How long would that have taken otherwise? Do you see now how you can code faster by automating it and combining powerful tools? Let’s look at some other cool search options find has to offer:
Other Examples
view plaincopy to clipboardprint?
1.
# find files changed in the last 1 day
2.
find . -ctime -1 -type f
3.
4.
#find files larger than 1 Mb in /tmp
5.
find /tmp -size 1M -type f
6.
7.
#find files newer than main.css in ~/src
8.
find ~/src -newer main.css
# find files changed in the last 1 day
find . -ctime -1 -type f
#find files larger than 1 Mb in /tmp
find /tmp -size 1M -type f
#find files newer than main.css in ~/src
find ~/src -newer main.css
Conclusion
By itself, find is only as good as say… Google Desktop. The real power, as with other shell tools, is the ability to combine with other tools seamlessly. Effective use of tools like find very often make the difference between an average programmer and one that is 10x more effective (actual multiples up for debate).
These are just some of the basic features of find. Take advice from Chris Coyier and use your new power responsibly. Find is a beautiful tool.