Search code examples
bashdivisioncut

Division by using 2 cut variables


I have the following code :

#!/bin/bash
pontos=$(cat condutores.txt | cut -d ":" -f 10)
nviagens=$(cat condutores.txt | cut -d ":" -f 9)
divisao=$((pontos / nviagens))
echo $divisao

I want to divide the 10th column of each line with 9th column of condutores.txt. Save it in a variable and check if the number is less than 5 . However the division does not work properly.


Solution

  • you could do this in one line using awk! Suppose I have sample data (which I am using to mimic yours):

    1       15      18
    2       17      6
    3       14      98
    4       17      25
    5       9       3
    

    This is how you divide column 3 by column 2 using awk:

    awk '{print $3/$2}' example_file.txt
    

    prints to standard output:

    1.2
    0.352941
    7
    1.47059
    0.333333
    

    Now say from this I wanted only those values which were less than 1:

    awk '{if ($3/$2 < 1) print $0}' awk_tester.txt
    

    returns the full rows:

    2       17      6
    5       9       3
    

    now if we want the actual value:

    awk '{if ($3/$2 < 1) print $3/$2}' awk_tester.txt
    

    returns:

    0.352941
    0.333333
    

    If your field separator is ':' just add this to the beginning of each awk command:

    -F ':'
    

    like so:

    awk -F ':' '{if ($3/$2 < 1) print $3/$2}' awk_tester.txt