Archive

Archive for the ‘Perl’ Category

convert_frames

June 3rd, 2010 No comments

This small perl script is really just an example of using Image::Magick to crop and convert a sequence of images to prepare them for insertion into a video file. I used it for my PyODE Example. You could easily write this as a one-line command if desired.

#!/usr/bin/perl
#
# convert_frames

use Image::Magick;

$imgdir = "frames";
$prefix = "pyode_ex3";

$| = 1;

while ($infile = <$imgdir/$prefix.*.tif>) {
    print "$infile -> ";
    ($outfile = $infile) =~ s/\.tif$/.png/;

    $image = Image::Magick->new;
    $x = $image->Read($infile); warn "$x" if ($x);
    $x = $image->Crop(geometry=>'640x360+0+30'); warn "$x" if ($x);
    $x = $image->Write($outfile); warn "$x" if ($x);

    unlink($infile);
    print "$outfile \n";
}
Categories: Perl Tags:

Find + Grep = findgrep

May 7th, 2010 2 comments

Here’s a small Perl script to (recursively) find text within files under a directory tree.

Yes, I know you can do a:

find <startpath> -name <fileglob> -print0 | xargs -0 grep <pattern>

… but that lists the filename for every match. Plus this has syntax highlighting and is easier to remember!

findgrep [options] <pattern> <startpath> <fileglob>

Here’s the code:

#!/usr/bin/perl
#
# findgrep [options] string [startpath] [fileglob]

use File::Find;
use Getopt::Std;
use Term::ANSIColor qw(:constants);

my $progname = $0;
$progname =~ s/.*\///;   # use basename only
$progname =~ s/\.\w*$//; # strip extension, if any

unless (getopts("hip", \%args)) {
    usage();
}

usage() if $args{h};

my $caseins   = $args{i};
my $progress  = $args{p};

my $string    = $ARGV[0];
my $startpath = $ARGV[1];
my $fileglob  = $ARGV[2];

$| = 1; # Set $OUTPUT_AUTOFLUSH on

$i = 0;

sub rgrep {
    return if (scalar(grep(/^$File::Find::dir$/, @Dircache)));

    push(@Dircache, $File::Find::dir);

    @L = glob($fileglob);

    $newline = 0;

    foreach (@L) {
        open(F, "<$_");
        if ($caseins) {
            @M = grep(/$string/i, <F>);
        } else {
            @M = grep(/$string/, <F>);
        }
        if (@M) {
            print "\b" x 10 , " " x 10 if ($progress);
            print BOLD, BLUE, "\n$File::Find::dir/$_", RESET, "\n";
            print @M;
            $newline = 1;
        }
        close(F);
    }
    if ($progress) {
        print " " x 10 if ($newline);
        printf("%s%s%s","\b" x 10, "." x ($i % 10 + 1), " " x (9 - ($i % 10)));
    }
    $i++;
}

print " " x 10 if ($progress);

find(\&rgrep, $startpath);

print "\n";

sub usage
{
    die << "EOT";
Usage: $progname [options] string [startpath] [fileglob]

Options:
  -h        Print this message
  -i        Case insensitive
  -p        Progress indicator
EOT
}
Categories: Perl Tags: