I have a problem that can be equaled to the problem of multiplying by ten a number. The first approach would be:
perl -pi -e 's/(\d+)/\1 0/g' myfile.txt
but this introduces an extra space and I can not put \10 because such group does not exist. My solution was this workarou开发者_如何学编程nd
perl -pi -e 's/(\d+)/\1\l0/g' myfile.txt
to lower case 0 but I'm sure there is a proper way that I'm not aware of.
Regards.
You are supposed to use the $1
form instead of \1
in substitutions. This is in fact one of the reasons why: with the variable form, you can say ${1}0
.
Don’t use the \1
notation on the RHS of a substitution. Use $1
.
There is, in general, an ambiguity issue between backrefs and octal notation. Or was. This is now solved.
In recent versions of Perl, when you need to unambiguously mean a backreference, you can use \g{1}
, and when you need to unambiguously mean an octal number, you can use \o{1}
.
You can use the /e
modifier:
perl -pi -e 's/(\d+)/$1 * 10/ge' myfile.txt
See also Warning on \1 Instead of $1
I wanted to expand on eugene's answer just for a little more accuracy to include digits. Especially if you were to do something other than multiply by ten, like divide by half.
perl -pi -e 's/(?<!\d|\.)(\d+(?:\.\d+)?)(?!\d|\.)/$1 * 10/ge' file.txt
Also here is the version to ignore colors in hex format or percentages. Handy if you're modifying css.
perl -pi -e 's/(?<!#|\d|\.)(\d+(?:\.\d+)?)(?!%|\d|\.)/$1 * 10/ge' file.txt
精彩评论