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?
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"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With