Find numbers in a file and change their value with perl

时间:2015-06-15 15:02:30

标签: regex perl

I have a file with some data in it but there are a bunch of annoying numbers that are less than one which I wanted to just change to 1 instead of manually doing it. I was wondering how you would do this in perl.

I tried using something like this

perl -pe 's/\d+/$& < 1 ? $&=1 : $&/g' file

This basically just finds all numbers and then checks if they are less then 1. If so then set it to 1 and if not leave it alone. Unfortunately, it will not allow $&=1 to happen since it is a readonly. Is there something else in perl that would achieve this effect? Example input:

this 1 is a 7 file that
has 0.5 some numbers 4
that are 0.3 less 0.1 than 0.9 
one as you see 1.1

Output:

this 1 is a 7 file that
has 1 some numbers 4
that are 1 less 1 than 1 
one as you see 1.1

2 个答案:

答案 0 :(得分:2)

\b0\.\d+\b

You can try this.Replace by 1.See demo.

https://regex101.com/r/hI0qP0/29

答案 1 :(得分:2)

You can just match the numbers that are less than one.. and replace with 1:

perl -pe 's/\b0\.\d+/1/g' file

See DEMO