Aivaras
Aivaras

Reputation: 125

Perl replace digits in document with math

I have .csv file in which I'm trying replace all instances of specific value for e.g. height:

"_height","10"
"_height","100"

I need to divide value by 2.54 and round result to nearest whole number. So far managed to write this one liner, just not sure how to do rounding.

perl -pi.bak -e 's|((?<="_height",").[0-9.]+)|($1)/2.54|eg' file

Upvotes: 1

Views: 85

Answers (1)

zdim
zdim

Reputation: 66899

Use sprintf "%0.f", $num to round

 perl -pe's{"_height","\K(\d+)}{sprintf "%0.f", $1/2.54}eg' input.csv

This uses \K form of the lookbehind.

If there is any more than this to process I'd recommend to parse the CSV file properly with a module. A good choice is Text::CSV, best with the Text::CSV_XS backend.

Upvotes: 3

Related Questions