[TxMt] help with perl search/replace

Paul McCann paul.mccann at adelaide.edu.au
Mon May 22 02:55:12 UTC 2006


Oliver wrote...

> I tried that, but this does not allow me to use "^" to denote the
> beginning of a line, which is critical to some of the search/replace
> things I'm doing.

In a multiline string you need to tell the perl interpreter that "^"
should match the beginning of a line within the string: to do that add
the "m" ("multiline") flag to your regular expression. You probably
also want to add a "g" ("global") flag to replace every occurrence in
the (big, multiline) string.

So something like

perl -pe 'BEGIN{$/=undef}; s/^\d+/some_digits /mg'

will replace any digits at the beginning of any lines of your text
with the string "some_digits ".

Here's another example that might help make things clearer

========================================================================
#!/usr/bin/perl
use strict;
use warnings;
my $string = "Something\nwith\nembedded newlines";
$string =~s/^(.)/* Beginning with $1 : $1/gm;

print $string;
======================Output=====================================

* Beginning with S : Something
* Beginning with w : with
* Beginning with e : embedded newlines

========================================================================

The only other flag of interest in such substitutions is the "s"
("single line(?)") flag, which allows the "." (ie, dot) metacharacter
to match a newline character. (Usually it won't match a newline.)This
is useful if you wish to match something that can break across lines,
or something that *has* to bridge lines.

Cheers,
Paul



More information about the textmate mailing list