Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWK Randomly choose 1 of 2 actions when condition is met

Tags:

bash

awk

I can substitute a value with another one in a file when my condition is met with this:

awk '{if (length($4)*2+1 != length($5) && $10 ~ /^1\/2/) sub("1/2","1/1"); print}' MyFile

Which replaces "1/2" with "1/1" in lines where my 2 conditions are true.

There are several such cases in my files, and what I would really like to do is to replace "1/2" with "1/1" in roughly half of the cases, while replace "1/2" with "2/2" in roughly the other half of the cases. That is, randomly choose one of the 2 possible actions sub("1/2","1/1") or sub("1/2","2/2"). Is this possible in any way?

Many thanks!

like image 797
FatihSarigol Avatar asked Jan 01 '26 07:01

FatihSarigol


1 Answers

awk '
    length($4)*2+1 != length($5) && $10 ~ /^1\/2/ {
        sub("1/2", rand() < 0.5 ? "1/1" : "2/2")
        print
    }
' MyFile
like image 153
glenn jackman Avatar answered Jan 03 '26 03:01

glenn jackman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!