简体   繁体   中英

Trying to make a substitution using perl

I have this text:

rojo

I want to make a substitution and turn it into:

rojo77

So I'm trying this:

perl -pi.bak -e "s/(ojo)/$177/g" oven.txt

If I wanted to replace with text instead of with 77, I would have no problem, but being a number I get this as a result:

r

I mean, it matches ojo , but replacement isn't working, so everything matched just gets deleted. How can I use $1 and use a number next to it?

Please help!

As a starter: since you know in advance the exact string part that you are trying to match, you don't actually need the substitution variable:

s/ojo/ojo77/

But if you wanted to use the substitution variable, you could do:

s/(ojo)/${1}77/

As commented by zdim , this can also be expressed using special assertion \K , which basically means Keep the stuff left :

s/ojo\K/77/

There a nice trick you can use with substitutions if you don't want to replace part of the pattern. The \K excludes from the replacement the part of pattern that comes before it:

perl -pi.bak -e "s/ojo\K/77/g" oven.txt

I write more about it in Ignore part of a substitution's match

Besides that, remember how Perl figures out a variable name. It takes all the legal identifier characters after the sigil. Since 177 is a legal variable name (even though you don't have that many captures), that's the name you get. To set apart the variable name from the rest of the text, you can surround the variable name with braces (sigil still outside):

"r$177"   # variable named 177
"r${1}77" # variable 1 

There is another way using e to concatenate the values in replacements.

s/(ojo)/$1.77/eg; # '.' dot will merge/concatenate the values from left and right 

Thanks for pointing out champ zdim in my box comments:

s/(ojo)/$1.q(77)/eg;

Evaluates the replacement as if it were a Perl statement, and uses its return value as the replacement texte

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM