Search code examples
unixif-statementawkcut

Awk with combination of cut and if


I have a file test.txt that contains :

1    1:?    1:0    0.762
2    1:?    2:1    0.754
3    1:?    2:1    0.848
4    1:?    1:0    1
5    1:?    2:1    0.851 

In the third column, I try to retrieve the number after : and according to its value, I have to apply a different calculation on the last column. If it is a 0 then I have to return the value in column 4 by subtracting 1. And if it is a 1, then I have to return the value of the column 4.

I can retrieve the number after the : with the following command:

awk '{print $3}' test.txt | cut -d: -f 2

But I don't know how to continue. How can I do that?


Solution

  • awk 'split($3,a,":"){print a[2]?$4:$4-1}' file
    

    or if you still want other field

    awk 'split($3,a,":"){$4=a[2]?$4:$4-1}1' file
    

    or even

    awk 'split($3,a,":")&&!a[2]{$4--}1' file
    

    ANOTHER

    Only $4

    awk '{$0=$4-($3~/:0$/)}1' file
    

    Line

    awk '{$4-=($3~/:0$/)}1' file