On Tue, Aug 14, 2001 at 12:25:48PM -0500, Jay Strauss wrote:
> Is there any way (in perl) to do a substitution like if you find this,
> replace it with that, else replace it with something else?
>
> For example I have a bunch of lines like:
>
> initial 256
> initial 512
> initial 1024
> initial 2048
>
> I want to match on /initial\s+\d+/ and replace 256 with 4092 but replace all
> the other numbers with 1024. I don't know (ahead of time) what the numbers
> are, I just know I want to replace a specific number with X and the rest
> with Y.
You can use s/(?<=initial\s+)(\d+)/ $1 == 256 ? "4092" : "1024" /e;
The (?<=foo) is a lookbehind assertion, and matches only when the
pattern is preceded by foo; but isn't itself included in the match
string. The 'e' switch allows you to use Perl code to generate the
substitution. This is a newer feature, and not available in older
Perl versions (such as the one I have available at the moment - thus,
the line above is untested).
Micah