Mailing List Archive

Support open source code!


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: search/replace



Sorry for missing the nomikai, folks. Too much work to do.

On Fri, Oct 20, 2000 at 07:29:19PM +0900, Tony Laszlo wrote:
> Hi folks. 
> 
> I have to do a search and replace on about 
> 30 keywords which appear in some 30 files. 
> Most of the work is on English text, but 
> maybe five of the keywords will be in 
> Japanese. I think emacs can do this without 
> too much fuss, but I haven't been using emacs 
> much lately and am wondering if there might be 
> another application which is particularly 
> good for this task. 
> 
> Any suggestions? 

perl, maybe?

#! /usr/bin/perl -w

# this script has not been tested. it's pretty tame perl code, though, so
# it should be easy to iron the kinks out of it.

use strict;

my @example.com = ("file1.txt","file2.txt","file3.txt",....);

my %replace_list = ("old1", "new1",
                    "old2", "new2",
		    "old3", "new3"...);

# make this variable blank if you're willing to have the script overwrite the
# old files with the new version.
my $chicken = ".new";

########################
# begin program

undef $/;   # search-and-replace in the entire file at a time
            # this assumes that the individual files aren't
	    # ridiculously large

foreach my $fn (@example.com) {

    open IN, $fn
                        or die "can't open $fn for reading\n";

    # slurp in the entire file
    my $lines = <IN>;
    close IN;

    # cycle through the s/r list and do search-and-replace
    foreach my $k (keys %replace_list) {
        $lines =~ s/$k/$replace_list{$k}/eg;
    }

    # overwrite old file or create new file, your choice.
    open OUT, ">$fn$chicken"
                        or die "can't open $fn$chicken for writing\n";    
    print OUT $lines;
    close OUT;
    
}

-- 
Shimpei Yamashita                               http://www.shimpei.org/


Home | Main Index | Thread Index

Home Page Mailing List Linux and Japan TLUG Members Links