awkconditional-statementstac

Search and Print by Two Conditions using AWK


I have this file:

         - - - Results from analysis of weight - - -
 Akaike Information Criterion   307019.66 (assuming 2 parameters).
 Bayesian Information Criterion 307036.93

                 Approximate stratum variance decomposition
 Stratum     Degrees-Freedom   Variance      Component Coefficients
 id                 39892.82    490.360         0.7     0.6     1.0
 damid                  0.00    0.00000         0.0     0.0     1.0
 Residual Variance   1546.46    320.979         0.0     0.0     1.0

 Model_Term                             Gamma         Sigma   Sigma/SE   % C
 id                     NRM_V 17633  0.18969       13.480       4.22   0 P
 damid                  NRM_V 17633  0.07644       13.845       2.90   0 P
 ide(damid)             IDV_V 17633  0.00000       32.0979      1.00   0 S
 Residual               SCA_V 12459  1.0000        320.979     27.81   0 P

And I Would Like to print the Value of Sigma on id, note there are two id on the file, so I used the condition based on NRM_V too.

I tried this code:

tac myfile | awk '(/id/ && /NRM_V/){print $5}'

but the results printed were:

13.480
13.845

and I need just the first one


Solution

  • Could you please try following, I have added exit function of awk here which will help us to exit from code ASAP whenever first occurrence of condition comes, it will help us to save time too, since its no longer reading whole Input_file.

    awk '(/id/ && /NRM_V/){print $5;exit}' Input_file
    

    OR with columns:

    awk '($1=="id" && $2=="NRM_V"){print $5;exit}' Input_file
    


    In case you want to read file from last line towards first line and get its first value then try:

    tac Input_file | awk '(/id/ && /NRM_V/){print $5;exit}'
    

    OR with columns comparisons:

    tac Input_file | awk '($1=="id" && $2=="NRM_V"){print $5;exit}'