john
john

Reputation: 45

Perl script for normalizing negative numbers

I have several large csv files in which I would like to replace all numbers less than 100, including negative numbers with 500 or another positive number.

I'm not a programmer but I found a nice perl one liner to replace the white space with comma 's/[^\S\n]+/,/g'. I was wondering if there's any easy way to do this as well.

Upvotes: 0

Views: 459

Answers (2)

poiu2000
poiu2000

Reputation: 980

The following works for me, assuming there are 2 files in the directory:

test1.txt:

201,400,-1
-2.5,677,90.66,30.32
222,18

test2.txt

-1,-1,-1,99,101
3,3,222,190,-999
22,100,100,3

using the one liner:

perl -p -i.bak -e 's/(-?\d+\.?\d*)/$1<100?500:$1/ge' *

-p will apply the search-replace process to each line in each file, -i.bak means do the replacement in the original files and backup those files with new files having .bak extension. s///ge part will find all the numbers (including negative numbers) and then compare each number with 100, if less than 100 then replace it with 500. g means find all match numbers. e means the replacement part will be treated as Perl code. * means process all the files in the directory

After executed this one liner, I got 4 files in the directory as:

test1.txt.bak test1.txt test2.txt.bak test2.txt

and the content for test1.txt and test2.txt are:

test1.txt

201,400,500
500,677,500,500
222,500

test2.txt

500,500,500,500,101
500,500,222,190,500
500,100,100,500

Upvotes: 0

Miller
Miller

Reputation: 35198

Using Windows formatting for a perl 1-liner

perl -F/,/ -lane "print join(q{,},map{/^[-\d.]+$/ && $_ < 100 ? 100: $_} @F),qq{\n};" input.csv > output.csv

Upvotes: 1

Related Questions