Find Options

Among the co­re-u­til­s, find is one of the most use­ful co­m­man­d­s. Thou­gh I use the ba­sic func­tion­s ­most of the ti­me, find has a wi­de ran­ge of pa­ra­me­ter­s, and it co­mes in handy not on­ly for fin­din­g ­fi­le­s, but al­so for ope­ra­ting a bun­ch of them at on­ce. He­re is a ve­ry sim­ple exam­ple.

Ima­gi­ne you ha­ve to mo­ve many fi­les to a di­rec­to­r­y, but they all ca­ll di­ffe­rent so a glob is no use, an­d ­ma­nua­lly mo­ving all of them is not an op­tio­n. A po­s­si­ble appro­ach would be to lo­ca­te the first of the ba­tch (for exam­ple by run­ning ls -l­r­­th). Su­ppo­se the first one of the ba­tch is ca­lled /t­m­p/­che­ck­point (for this exam­ple ­le­t’s as­su­me the fi­les re­si­de at /t­mp).

The co­m­mand would be:

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

The -ty­­pe f part is im­por­tant in or­der not to mo­ve the en­ti­re di­rec­to­ry (find on­ly the fi­le­s). Then we ha­ve the -a­­newer that re­cei­ves a fi­le as a pa­ra­me­te­r, and it wi­ll fil­ter for tho­se fi­les who­se ­mo­di­fi­ca­tion da­te is grea­ter than the fi­le us­ed as an exam­ple (hen­ce, this must be the start of the ba­tch), an­d ­fi­na­lly the -exec part is in­te­res­ting be­cau­se as men­tio­ned at the be­gin­nin­g, it allo­ws to per­for­m ar­bi­tra­ry ope­ra­tions on the group of fi­les (in this ca­se to mo­ve them to ano­ther lo­ca­tio­n, bu­t o­ther ac­tions su­ch as mo­di­fi­ca­tion­s, sed, etc. are al­so po­s­si­ble).

Ano­ther trait I like about find is that pre­sen­ts a se­cu­re and we­ll-­de­fi­ned in­ter­fa­ce, mea­ning that in ­so­me ca­ses I can first che­ck the re­sul­ts prior to exe­cu­te an ac­tio­n. For exam­ple, if we would like to che­ck ­for de­le­ting so­me un­ne­ce­ssary fi­le­s:

find . -name "*.pyc"

By is­suing this co­m­mand we list so­me fi­les to era­se. And then we can sim­ply do that by a­ppen­ding -de­­le­­te to the ve­ry sa­me co­m­man­d.

This is just the tip of the ice­berg of the things that are po­s­si­ble by means of the find co­m­mand an­d i­ts va­rious op­tion­s.