Reputation: 89
I am having a file with numbers in MB units and I wanted to make them in GB then I found a very interesting perl to do this
perl -pe 's{(?<!\d)(\d+(?:\.\d+)?)(?!\d)}{$1/1024}ge'
But I still need to round the results 2 digits after the dot
Currently, results like 260.676914215088
I tried some other Unix tools like cut
and bc
but it would be better if done within Perl.
BTW the file contains numbers and strings and the above Perl is working as expected but I still need to round results.
I would appreciate if someone helped with the above perl statement as I am already using it to change between different units
Upvotes: 1
Views: 148
Reputation: 54371
You can embed the sprintf
call into your substitution. You already have the /e
modifier, so you can run that command in the substitution part and pass it the calculation you're doing.
# VVVVVVVVVVVVVVVV V
perl -pe 's{(?<!\d)(\d+(?:\.\d+)?)(?!\d)}{sprintf("%.02f", $1/1024)}ge'
See it in action here:
$ echo "1234567" | perl -pe 's{(?<!\d)(\d+(?:\.\d+)?)(?!\d)}{sprintf("%.02f", $1/1024)}ge'
1205.63
Upvotes: 3
Reputation: 912
Since you're dealing with a one-liner, there's no limit to the number of pipes you can give it, so just add this to your line: perl -n -e 'printf ("%.2f\n",$_)'
meaning
perl -pe 's{(?<!\d)(\d+(?:\.\d+)?)(?!\d)}{$1/1024}ge'| perl -n -e 'printf ("%.2f\n",$_)'
e.g.
> echo "12014.324\n10123123.1\n20123.5555" | perl -pe 's{(?<!\d)(\d+(?:\.\d+)?)(?!\d)}{$1/1024}ge' | perl -n -e 'printf ("%.2f\n", $_)'
11.73
9885.86
19.65
Upvotes: 0