Feature idea
F@lk Brettschneider
gigafalk at yahoo.com
Mon Dec 17 15:31:02 UTC 2001
Gregor Zeitlinger wrote:
>
> On Mon, 17 Dec 2001, F at lk Brettschneider wrote:
> > > Are there plans for
> > >
> > > 1) Replace in files (I really miss that one!)?
> > No.
> Is this hard to implement. Or is there another easy way of doing such
> things? Every time I want to change a function name in every file of a
> project, it's a mess. So I'm considering doing it myself if it's fairly
> easy.
I can help you with a perl script. See the attachment.
Maybe not very beaut but it works at least for me. :-)
Call for instance:
./replace -R -f '.+\.cpp' -s "OldText" -r "NewText" *
to recursively replace all strings "OldText" with "NewText" in all .cpp
files.
(Note that it handles regular expressions but not shell script
expressions.)
Ciao,F at lk
-------------- next part --------------
#!/usr/bin/perl
#
# replace stuff in files
use Getopt::Std;
# global variables
my %opts;
# Usage($errormessage);
# Print usage information, preceded by an error message and exit
sub Usage
{
print "replace: @_\n";
print "Usage replace [-R] [-f \"filereg\"]\n";
print " -s \"searchreg\" -r \"replaceby\" files\n";
print " -R ... replace recursively\n";
print " -f \"filereg\" ... only replace in files that match\n";
print " -s \"searchreg\" ... regular expression to match\n";
print " -r \"replaceby\" ... string to replace\n";
exit(-1);
}
# ReplaceFile($file);
# Print usage information, preceded by an error message and exit
sub ReplaceFile
{
my ($name) = @_;
if (-f $name)
{
if ( (!exists $opts{'f'}) ||
(exists $opts{'f'} && $name =~ m/$opts{'f'}/)
)
{
print "replacing: $name\n";
my @list, @newlist;
local * FILE;
open(FILE, "<$name");
@list = <FILE>;
close(FILE);
open(FILE, ">$name");
foreach $_ (@list)
{
s/$opts{'s'}/$opts{'r'}/;
print FILE $_;
}
close(FILE);
}
}
elsif ( -d $name && exists $opts{'R'} )
{
local * DIR;
my @dirlist;
opendir(DIR, $name);
@dirlist = readdir(DIR);
closedir(DIR);
print "DIR: $name\n";
foreach $_ (@dirlist)
{
if ( !(m/\.$/) )
{
ReplaceFile("$name/$_");
}
}
}
}
# check options
Usage("help info") unless getopts("Rf:s:r:", \%opts);
Usage("Must specify files") if ($#ARGV<0);
Usage("Must specify required options") unless (exists $opts{'s'}
&& exists $opts{'r'});
for ($i = 0; $i<=$#ARGV; $i++)
{
ReplaceFile($ARGV[$i]);
}
More information about the KDevelop-devel
mailing list