Reputation: 21
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
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.$10
rather than $1
. Use curlies to disambiguate (${1}0
).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
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.$1
is used instead of \1
on replacement side (see perldoc note here about this). Upvotes: 2