Marko8119
Marko8119

Reputation: 21

Perl one-liner to specify decimal places

I'm modifying a large txt file. Is there a one-liner in which you pad a string pattern to the right with zeros? For instance, to go from one or two decimal places to three. e.g. from 0.21 to 0.210 or 0.5 to 0.500? The code I was trying:

perl -p -i -e 's/(\.\d{1,2})/\10/g' myFile.txt

Thanks in advance for any help :)

Upvotes: 1

Views: 599

Answers (2)

ikegami
ikegami

Reputation: 386561

  • \1 should be $1. It makes no sense to use \1 in the replacement expression. As indicated by a warning, doing so is a bug.
  • It's seeing $10 rather than $1. Use curlies to disambiguate (${1}0).
  • That always adds one zero, even when you need two.

Solutions:

perl -i -pe's/\.\d(\d)?\K/ defined($1) ? "0" : "00" /eg' myFile.txt
perl -i -pe's/\.(\d{1,2})\K/ "0" x (3 - length($1)) /eg' myFile.txt
perl -i -pe's/\.\d(?!\d)\K/0/g; s/\.\d\d\K/0/g;' myFile.txt

Upvotes: 2

doubleDown
doubleDown

Reputation: 8408

As Barmar said in the comment, you can use sprintf to specify the number of decimal places.

perl -p -i -e 's/(\d+\.\d+)/sprintf "%.3f", $1/eg' myFile.txt

Notes:

  • %.3f means a floating point number with 3 decimal places.
  • e flag means evaluate the replacement side as an expression.
  • Also note that you have to capture the entire number (not just digits after decimal point) for this to work.
  • $1 is used instead of \1 on replacement side (see perldoc note here about this).

Upvotes: 2

Related Questions