in reply to Word replace - notetab light vs perl
you can use some cmd line swithces and arguments and shell redirection (this particular one works in any common shell that I know of, including command.com):open(FH, "wrongs") or die $!; open(FH2, ">wrongs2") or die $!; while ($line = <FH>) { $line =~ s/wrongs/wrongs3/; print FH2 "$line"; } close (FH); close (FH2);
orperl -lpe 's/wrongs/wrongs3/' wrongs >wrongs2
if you want in place editing. But under Windows AFAIK you will have to do (something like):perl -lpi -e 's/wrongs/wrongs3/' wrongs
andperl -lpe "s/wrongs/wrongs3/" wrongs >wrongs2
respectively instead; i.e. use double quotes for quoting and cannot do in place editing withou backup.perl -lpi.bak -e "s/wrongs/wrongs3/" wrongs
Modified my Perl code to count the number of replacements as well as added benchmarking:The code above can easily be adapted to show the count:
For the benchmark, it's not just that easy. That's what Benchmark.pm is for, and indeed it works by repeating the code to be tested a suitable number of times. But if the task takes long enough, then bash's time command will suffice: here's a test on a file that's 3494270 lines long:perl -lpi '$c++ if s/wrongs/wrongs3/; END{warn "count=$c\n"}' wrongs
Unfortunately it's not available under command.com and cmd.exe, that I know.$ time perl -lpe '$c++ if s/sex/cool/; END{warn "count=$c\n"}' gse1.lo +g >/dev/null count=2840 real 0m19.062s user 0m16.736s sys 0m0.940s
Last, you may also want to count the number of substitutions when the /g global modifier is given. In that case
or else you may use the "highly experimental" </c>(?{ code })</c> regex feature:perl -lpi '$c+=s/wrongs/wrongs3/g; END{warn "count=$c\n"}' wrongs
but there's really no need for it here...perl -lpi 's/wrongs($c++)/wrongs3/g; END{warn "count=$c\n"}' wrongs
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Word replace - notetab light vs perl
by kiat (Vicar) on Oct 06, 2005 at 10:27 UTC |