Find Options

Among the core-u­til­s, find is one of the most use­ful com­mand­s. Though I use the ba­sic func­tion­s ­most of the time, find has a wide range of pa­ram­e­ter­s, and it comes in handy not on­ly for find­ing ­files, but al­so for op­er­at­ing a bunch of them at once. Here is a very sim­ple ex­am­ple.

Imag­ine you have to move many files to a di­rec­to­ry, but they all call dif­fer­ent so a glob is no use, and ­man­u­al­ly mov­ing all of them is not an op­tion. A pos­si­ble ap­proach would be to lo­cate the first of the batch (for ex­am­ple ­by run­ning ls -l­rth). Sup­pose the first one of the batch is called /tm­p/check­point (for this ex­am­ple let’s as­sume the files re­side at /tmp).

The com­mand would be:

find /tmp -type f -anewer /tmp/checkpoint -exec mv '{}' <target_directory> \;

The -type f part is im­por­tant in or­der not to move the en­tire di­rec­to­ry (find on­ly the files). Then we have the -anew­er that re­ceives a file as a pa­ram­e­ter, and it will fil­ter for those files whose ­mod­i­fi­ca­tion date is greater than the file used as an ex­am­ple (hence, this must be the start of the batch), and ­fi­nal­ly the -ex­ec part is in­ter­est­ing be­cause as men­tioned at the be­gin­ning, it al­lows to per­for­m ar­bi­trary op­er­a­tions on the group of files (in this case to move them to an­oth­er lo­ca­tion, but other ac­tions such as mod­i­fi­ca­tion­s, sed, etc. are al­so pos­si­ble).

An­oth­er trait I like about find is that presents a se­cure and well-de­fined in­ter­face, mean­ing that in­ ­some cas­es I can first check the re­sults pri­or to ex­e­cute an ac­tion. For ex­am­ple, if we would like to check­ ­for delet­ing some un­nec­es­sary files:

find . -name "*.pyc"

By is­su­ing this com­mand we list some files to erase. And then we can sim­ply do that by ap­pend­ing -delete to the very same com­mand.

This is just the tip of the ice­berg of the things that are pos­si­ble by means of the find com­mand and its var­i­ous op­tion­s.