tonicebrian
tonicebrian

Reputation: 4795

How do you multiply by 10 using regular expressions?

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 workaround

   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.

Upvotes: 1

Views: 3907

Answers (4)

Soshmo
Soshmo

Reputation: 308

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

Upvotes: 0

tchrist
tchrist

Reputation: 80384

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

Upvotes: 5

geekosaur
geekosaur

Reputation: 61369

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.

Upvotes: 8

Eugene Yarmash
Eugene Yarmash

Reputation: 149736

You can use the /e modifier:

perl -pi -e 's/(\d+)/$1 * 10/ge' myfile.txt

See also Warning on \1 Instead of $1

Upvotes: 4

Related Questions