Skip site navigation (1)Skip section navigation (2)
Date:      Wed, 23 Jul 2003 13:20:40 -0700
From:      oremanj@get-linux.org
To:        "Scott I. Remick" <scott@sremick.net>
Cc:        questions@freebsd.org
Subject:   Re: search & replace on multiple files
Message-ID:  <20030723202040.GC1504@webserver>
In-Reply-To: <1gf6uzxb9h9ir.1okxodxnyrkv2.dlg@40tude.net>
References:  <1gf6uzxb9h9ir.1okxodxnyrkv2.dlg@40tude.net>

next in thread | previous in thread | raw e-mail | index | archive | help
On Wed, Jul 23, 2003 at 10:56:19AM -0400 or thereabouts, Scott I. Remick wrote:
> Hello... I'm trying to figure out a way to pull off the following:
> 
> I have a subdir with many different sorts of text files (some nested in
> additional subdirs, so recursion would be necessary) that need to have a
> search & replace done on them. What's a quick way to script a global search
> & replace on many/all text files in nested subirs? 

Hard way (tested):

#!/usr/bin/env perl

use File::Find;

find sub {
        -f $_ or return;
        my $file = $_;
        my $filebak = "${file}~";
        rename $file, $filebak or die "Can't rename $file to $filebak: $!\n";
        open FILEBAK, $filebak or die "Can't open $filebak: $!\n";
        open FILE, ">$file" or die "Can't write to $file: $!\n";
        while (<FILEBAK>) {

                # Replace OLD with the "search for" -- a regexp
                # Replace NEW with the "replace with"
                s/OLD/NEW/g;

                print FILE $_;
        }
}, ".";

# end replace.pl

Easy way (not tested):

find . -type f | perl -pi~ -e 's/OLD/NEW/g;'

-- Josh

> 
> Thanks!
> 
> _______________________________________________
> freebsd-questions@freebsd.org mailing list
> http://lists.freebsd.org/mailman/listinfo/freebsd-questions
> To unsubscribe, send any mail to "freebsd-questions-unsubscribe@freebsd.org"



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20030723202040.GC1504>