ChiseledAbs ChiseledAbs - 2 years ago 89
Perl Question

How to modify the matched pattern

Just wondering if there is a handy way to modify matched pattern variable in Perl one liner. For instance in the string

I'd like to replace
(output abce) using a command looking like this :

echo "abcdef" | perl -pne 's/(def)/{command that trims first and last character of $1 and returns it as a string for perl to use it as a replacement}/'

It would be easy to use such functionality to perform various formating tasks. Can we do this in sed ?

Answer Source

This is easy in Perl with the /e flag:

echo 'abcdef' | perl -pe 's/(def)/substr $1, 1, -1/e'

e tells perl to parse the replacement part as a block of code, not a string. You can put arbitrary code in there.

But your concrete task (trimming the first and last character) can also be done like this:

echo 'abcdef' | perl -pe 's/d(e)f/$1/'

(Also, perl -p already implies -n. No need to specify both.)

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