1

I'm a new awk user, so there are a lot of things that I don't now how to do. I need to print a part of the line that follows certain pattern. For example I have this data as a part of the file Number of q in the star = 1

 List of q in the star:
      1   0.000000000   0.000000000   0.000000000

      Dielectric constant in cartesian axis

      (      12.793033167       0.000000000       0.000000000 )
      (       0.000000000      12.793033167       0.000000000 )
      (       0.000000000       0.000000000      12.793033167 )

I need to extract the number 12.793033167 only and my pattern is "List of q in the star".

I've found the solution how to extract the whole line after pattern:

awk 'c&&!--c;/pattern/{c=N}' file

However I do not understand how to update it in a way to print only 2nd column (Like with print $2).

Can anyone offer a good solution? Also it would be nice to have some detailed explanation how it works overall.

1 Answers1

3

You're almost there

$ awk 'c&&!--c{print $2} /List of q/{c=5}' file

12.793033167

$2 is the second field.

c&&!--c is a smart counter, substitute the value c=5 after pattern match will start the count down (initial value of c is zero).

5 && !4 -> false
4 && !3 -> false
3 && !2 -> false
2 && !1 -> false
1 && !0 -> true

action is triggered when the condition is true, exit value of c is 0.

You also need to know that for false && b b is not evaluated (short-circuit rules). --c pre-decrements the value. Ed Morton has a post with a lot more examples of the smart counters

Community
  • 1
  • 1
karakfa
  • 66,216
  • 7
  • 41
  • 56
  • And can you explain how this type of awk codes work? (Or better give a link with explanation - I'm sure I'm not the first one to ask). – Oleksandr Motornyi Feb 24 '16 at 14:48
  • Also It's possible that I will have a bit different (and more general) problem in the future - how to extract M lines (or certain fields in lines) starting from the Nth after the pattern (which include the case of M=0 - to include the pattern line). I assume it should like similar but I still don't now how exactly. – Oleksandr Motornyi Feb 24 '16 at 14:51
  • see the referenced post for that. – karakfa Feb 24 '16 at 14:55
  • OK, thank you very much. The one you proposed works well and with others I will deal later. – Oleksandr Motornyi Feb 24 '16 at 14:59
  • I've met also this solution http://stackoverflow.com/a/18569128/5975065 (for multiline printing) which I did not understand at all... It looks like it uses some features of regexp and awk and no such things as smart counters – Oleksandr Motornyi Feb 24 '16 at 15:02
  • that's a different approach, setting up the record structure with multiple lines. I added alternative answer to the same post, judge yourself which is easier to understand and extend stackoverflow.com/a/35605929/1435869 – karakfa Feb 24 '16 at 16:44