How to divide two columns with multiple ifs and send output to different files

Suppose the following columns, delimiter is one space (here for more readability I added more spaces):

col1 col2 col3 col4 col5  col6  col7 col8 col9 col10
1    P    0    0    1500  15000 0.5  0.0  200  name1
2    P    0    0    400   5000  0.7  0.2  150  name2
3    R    0    0    2000  2000  0.4  0.1  250  name3
4    R    0    0    5000  10000 0.2  0.3  600  name4
5    P    0    0    0     0     0.0  0.0  150  name5
6    R    0    0    6000  10000 0.1  0.0  120  name6
7    P    0    0    8     60    0.9  0.4  180  name7

The desired output should be something like this :

file1 (if {col6 / col5 equals or greater than 8}):

ratio for name1 is {ratio}.
ratio for name2 is {ratio}.

file2 (if {col6 / col5 is between 1 or 6}):

ratio for name3 is {ratio}.
ratio for name4 is {ratio}.
ratio for name6 is {ratio}.

file3 (if {col6 / col5 is zero}) (in this file, I mean if one of numbers is zero and we’ll have something like zero division error, they should be here:

ratio for name5 is Zero

file4 (if none of above if clauses matched, then it goes here) (in this case, it is between 6.00000…1 to 7.9999…):

ratio for name7 is {ratio}.

This is my try but I can only differentiate if is zero, is less than 10 or greater than 10.

awk 'NR!=1{printf "ratio for %s is %s.\n", $10, $6==0?"ZeroDivision":($6/$5>1)?$($6/$5):($6/$5)}' < /root/test_file

I prefer having multiple files, but if that’s a single file, it works too.

>Solution :

This awk should work for you:

awk '
NR==1 {next}
{
   r = (!$5 ? 0 : $6/$5)
   fn = "file4"
}
r >= 8 {fn="file1"}
r >= 1 && r<= 6 {fn="file2"}
!r {fn="file3"}
{
   print "ratio for", $NF, "is", r > fn
}' file

Output:

awk 'FNR == 1 {print "::", FILENAME, "::"} 1'  file{1..4}

:: file1 ::
ratio for name1 is 10
ratio for name2 is 12.5
:: file2 ::
ratio for name3 is 1
ratio for name4 is 2
ratio for name6 is 1.66667
:: file3 ::
ratio for name5 is 0
:: file4 ::
ratio for name7 is 7.5

Leave a Reply