TCLUG Archive
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [TCLUG:14107] Need help with Perl program



> > I am trying to learn Perl and I am having trouble solving what I
> > would think should be a simple problem.
> >
> > What I would like to do is create an array that has in it all of the
> > files in a directory and its subdirectories. To put it another way, I
> > am looking for the output of 'ls -R' placed into an array more or
> > less.
> 
> @out = `find . -print';  # replace . with the name of the directory if
> you aren't already in it
> 
> you'll probably want to chomp each array line to remove the \n, but I'd
> do that while you were doing other processing...

I've written this very script, for mass editing web sites, several
times myself.  A version is below.

--Mark

Mark Phillips @ Geometry Technologies, Inc.
550 Gilbert Building, 413 Wacouta St., St. Paul, MN 55101
Phone: 651-223-2884  Fax: 651-292-0014
mbp@geomtech.com       http://www.geomtech.com

------------------------------------------------------------------------
#! /usr/bin/perl

# usage: greplace DIR STRING REPLACEMENT

# This script assumes STRING is a literal string to be replaced.
# (If you want to allow a regular expression instead of a string,
# remove the \Q and \E below.)

$DIR	     = shift
$STRING      = shift;
$REPLACEMENT = shift;

open(FILES, "find $DIR -name '*.html' -print|");
chomp(@files = <FILES>);
close(FILES);

# That does the chomp in one fell swoop, and specifying '-name
# *.html' in the "find" makes sure that you only get html files.

foreach $file (@files) {
    # read the file into the $content buffer
    $content = "";
    open(FILE, "<$file");
    while (<FILE>) { $content .= $_; }
    close(FILE);

    # if it has the $STRING in it, do the replacement
    if ($content =~ /\Q$STRING\E/) {
	# start by renaming the original file to have suffix '.old'
	rename($file, "$file.old");
	# make the changes in $content, which hold the contents of
	# the orig file
	$content =~ s/\Q$STRING\E/$REPLACEMENT/gm;
	open(OUT, ">$file");
	print OUT $content;
	close(OUT);
    }
}