ChiseledAbs ChiseledAbs - 5 months ago 10
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 ?


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.)