Jasmine Lognnes Jasmine Lognnes - 1 year ago 68
Perl Question

Possible to not lose the matched string?

If I do

perl -i -slpe 's/$wgDBserver = "\K.*?"/$ip"/' -- -ip=$IP test

then I have to add the
on the replace side, as I do
on the matching side, and therefore lose the
, and therefore have to replace it again.


Is it possible to not having to add the
again my self?

Here is my test case:

$ IP="123.456.78.9" && \
echo -n '\n\n$wgDBserver = "";\naaa "123"\n\n\n' > test && \
perl -i -slpe 's/$wgDBserver = "\K.*?"/$ip"/' -- -ip=$IP test && \
cat test

$wgDBserver = "123.456.78.9";
aaa "123"

Answer Source

You should check "Look-Around Assertions" in perlre.

Use positive lookahead(?=):

(?=pattern) : A zero-width positive look-ahead assertion. For example, /\w+(?=\t)/ matches a word followed by a tab, without including the tab in $& .


So, here trailing " will match, but will not get captured in $&.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download