Replace column by random number addition

Here is my problem:-

I have a file with pipe separated values.

CR|20121021|079|ABC|N|DLS|00038|DLS|04750|1330597704|634234|634|0
CR|20121021|079|ABC|N|DLS|00038|DLS|05118|2071690102|354|351|3
CR|20121021|079|ABC|N|DLS|00038|DLS|05140|960051505|1088|1088|0
CR|20121021|079|ABC|N|DLS|00038|DLS|05158|2071690102|804|801|3
CR|20121021|079|ABC|N|DLS|00038|DLS|05858|589505306|473|473|0
CR|20121021|079|ABC|N|DLS|00038|DLS|26456|-1482184796|371|371|0
CR|20121021|079|ABC|N|DLS|00038|DLS|30036|1549556811|2001|1982|19
CR|20121021|079|ABC|N|DLS|00038|DLS|30038|1330597704|2460|24600|0
CR|20121021|079|ABC|N|DLS|00038|DLS|30130|218959107|1908|1894|14
CR|20121021|079|ABC|N|DLS|00038|DLS|30266|2071690102|468|468|0

Now I want to replace field: 10 (highlighted) by adding a random number to field number: 11. But the random number has to be generated based on decimal places of field: 11

E.g: In the first record, the 11th field value is 634234, so we have to generate a 4 digit random number and add to field number 11.

Hence if 11th field is

6 digits - random number should be 4 digits
5 digits - random number should be 3 digits
4 digits - random number should be 2 digits
3 digits - random number should be 1 digits

Please assist.

 perl -F'\|' -alne '{$num=sprintf("9"x(length($F[10])-2));$F[9]=$F[10]+int(rand($num));$"="|";print "@F";}' input_file
1 Like

@msabhi, It works! Thank you very much.

One last request, if the 11th field digit is less than or equal to 3 digits I still want to generate a 1 digit random number and add it.

Can you please help with that?

perl -F'\|' -alne '{$num=(length($F[10])<=3)?9:sprintf("9"x(length($F[10])-2));$F[9]=$F[10]+int(rand($num));$"="|";print "@F";}' input_file
1 Like
awk 'BEGIN {FS=OFS="|"; CONVFMT="%.0f"; srand()} {$10 += int(rand()*10^((x=length($11)-2)>0?x:1))} 1'

Regards,
Alister

1 Like