Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl's \K in bash function

When I do

function replace { ( perl -i -slpe 's/^$string.*\K/$add/' -- -string="$1" -add="$2" $3 ) } 

replace 'passwd:' 'files dns' /tmp/1

I get

passwd:     filesfiles dns
group:      files

which should have been

passwd:     files dns
group:      files

The input files is

passwd:     files
group:      files

Question

Can anyone explain why it doesn't do that?

like image 799
Sandra Schlichting Avatar asked Apr 01 '26 23:04

Sandra Schlichting


1 Answers

Your \K and .* are in wrong place altogether, what you have done is with ^$string.*\K is have matched the whole line(.* is greedy) before inserting the \K quantifier so that means the insertion happens after the whole line match. You should change it to be more effective as

perl -i -slpe 's/^$string\s+\K.*/$add/' -- -string="$1" -add="$2" "$3"

This way you take care of the proper spacing after the search string and add the replacement part after that. Also you don't need the function keyword in shell functions and also drop the () altogether and just do

replace () {
    perl -i -slpe 's/^$string\s+\K.*/$add/' -- -string="$1" -add="$2" "$3"
}
like image 144
Inian Avatar answered Apr 03 '26 15:04

Inian