home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book HomeLearning Perl, 3rd EditionSearch this book

B.26. Converting find Command Lines to Perl

A common task for a system administrator is to recursively search the directory tree for certain items. On Unix, this is typically done with the find command. We can do that directly from Perl, too.

The find2perl command, which comes with Perl, takes the same arguments that find does. Instead of finding the requested items, however, the output of find2perl is a Perl program that finds them. Since it's a program, you can edit it for your own needs. (The program is written in a somewhat odd style.)

One useful argument that's available in find2perl but not in the standard find is the -eval option. This says that what follows it is actual Perl code that should be run each time that a file is found. When it's run, the current directory will be the directory in which some item is found, and $_ will contain the item's name.

Here's an example of how you might use find2perl. Suppose that you're a system administrator on a Unix machine, and you want to find and remove all of the old files in the /tmp directory.[422] Here's the command that writes the program to do that:

[422]This is a task typically done by a cron job at some early-morning hour each day.

$ find2perl /tmp -atime +14 -eval unlink >Perl-program

That command says to search in /tmp (and recursively in subdirectories) for items whose atime (last access time) is at least 14 days ago. For each item, the program should run the Perl code unlink, which will use $_ by default as the name of a file to remove. The output (redirected to go into the file Perl-program) is the program that does all of this. Now you merely need to arrange for it to be run as needed.



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.