2

This one is asked many times and still I am unable to solve. A part of my file looks like:

 GKKRBSF:: ewrat=   0.00000 (<1 searchk, >1 searche)
           dirat=   0.00000 (Direct Summation ratio)
nhat,betah=  0.1000D+01 0.0000D+00 0.1000D+01      0.10000D+00
nhat,betah=  0.1000D+01 0.0000D+00 0.1000D+01      0.10000D+00
nhat,betah=  0.1000D+01 0.0000D+00 0.1000D+01      0.10000D+01
nhat,betah=  0.1000D+01 0.0000D+00 0.1000D+01      0.10000D+01
nhat,betah=  0.1000D+01 0.0000D+00 0.1000D+01      0.10000D+00

This is somewhere in between the file. I have to get $5 of first and n-th(say,3rd in this particular example) match of nhat,betah. For the first line, I can easily do a:

var_M=`awk '/nhat,betah=/{print  $5;exit}' filename`

But, how can I get the 3rd line and exit? I tried, from this thread, as:

var_M=`awk '/nhat,betah=/{j++}j=3{print  $5;exit}' filename`

And this is giving the 5th column of the 3rd line of the file, without matching the pattern. Surely I am missing something. Any help please?

Community
  • 1
  • 1
BaRud
  • 3,055
  • 7
  • 41
  • 89

1 Answers1

4

You can keep track of how many times it appeared:

$ awk '/nhat,betah=/{i++; if (i==3) {print $5; exit}}' file
0.30000D+01

Explanation

You almost had it, it was just a matter of putting the condition inside in a proper way:

From

var_M=$(awk '/nhat,betah=/{j++} j=3{print  $5;exit}' filename)
                                 ^

to

var_M=$(awk '/nhat,betah=/{j++} j==3{print  $5;exit}' filename)
                                 ^^

Note I changed the last column to 0.NumberOfLine to make it more clear which line it is outputting:

 GKKRBSF:: ewrat=   0.00000 (<1 searchk, >1 searche)
           dirat=   0.00000 (Direct Summation ratio)
nhat,betah=  0.1000D+01 0.0000D+00 0.1000D+01      0.10000D+00
nhat,betah=  0.1000D+01 0.0000D+00 0.1000D+01      0.20000D+00
nhat,betah=  0.1000D+01 0.0000D+00 0.1000D+01      0.30000D+01
nhat,betah=  0.1000D+01 0.0000D+00 0.1000D+01      0.40000D+01
nhat,betah=  0.1000D+01 0.0000D+00 0.1000D+01      0.50000D+00
fedorqui
  • 275,237
  • 103
  • 548
  • 598