Power of perl and unix commands
When you work every day with the unix environment you start to like it :-). After few years you can not work without the utilities that you have found in the environment. Yesterday, a friend of mine asked me to solve a problem for him. He has a bunch of files in a directory and in different subdirectories. He would like to change the permissions for all files that have the permissions 777 to 766, every other file should not be touched.
What to do ? After i have study the find command’s man page i went to find2perl command. This is a very powerfull preprocessor, it takes a bunch of options and produces a very good perl code.
With the use of find2perl the solutions is very easy:
$ find2perl mydirectory -type f -perl 777 -exec chmod 766 | perl
The above find2perl command produces following perl code:
#! /usr/bin/perl -w
eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
if 0; #$running_under_some_shell
use strict;
use File::Find ();
# Set the variable $File::Find::dont_use_nlink if you're using AFS,
# since AFS cheats.
# for the convenience of &wanted calls, including -eval statements:
use vars qw/*name *dir *prune/;
*name = *File::Find::name;
*dir = *File::Find::dir;
*prune = *File::Find::prune;
sub wanted;
sub doexec ($@);
use Cwd ();
my $cwd = Cwd::cwd();
# Traverse desired filesystems
File::Find::find({wanted => \&wanted}, 'test');
exit;
sub wanted {
my ($dev,$ino,$mode,$nlink,$uid,$gid);
(($dev,$ino,$mode,$nlink,$uid,$gid) = lstat($_)) &&
(($mode & 0777) == 0777) &&
-f _ &&
doexec(0, 'chmod','755');
}
sub doexec ($@) {
my $ok = shift;
my @command = @_; # copy so we don't try to s/// aliases to constants
for my $word (@command)
{ $word =~ s#{}#$name#g }
if ($ok) {
my $old = select(STDOUT);
$| = 1;
print "@command";
select($old);
return 0 unless
}
chdir $cwd; #sigh
system @command;
chdir $File::Find::dir;
return !$?;
}
Hope this helps you in your search.