Skip to content
Advertisement

Use awk command to get information below a pattern

I have a file with a wide range of information and I want to extract some data from here. I only will post here the interesting part. I want to extract IQ and JQ values as well as the J_ij[meV] value which is two lines above. I read this question How to print 5 consecutive lines after a pattern in file using awk where a pattern is used to extract information bellow and I was thinking doing something similar. My initial idea was:

awk '/IQ =/ { print $6,$12 }  /IQ =/ {for(i=2; i<=2; i++){ getline; print $11 }}' input.text > output.txt

Loop appears not to working

IT   IQ   JT    JQ   N1 N2 N3    DRX    DRY    DRZ     DR         J_ij [mRy]     J_ij [meV]

 IT =  1 IQ =  **1**                     JT =  1 JQ =  **1**

->Q = ( -0.250,  0.722,  0.203)   ->Q = ( -0.250,  0.722,  0.203)

1    1    1    1    0  0  0   0.000  0.000  0.000   0.000      0.000000000     **0.000000000**

 IT =  1 IQ =  **1**                     JT =  6 JQ =  **6**

 ->Q = ( -0.250,  0.722,  0.203)   ->Q = (  0.000,  1.443,  0.609)

  1    1    6    6   -1  0 -1  -0.250 -0.144 -0.406   0.498      0.135692822     **1.846194885**

 IT =  1 IQ =  **1**                     JT =  8 JQ =  **8**

  ->Q = ( -0.250,  0.722,  0.203)   ->Q = (  0.000,  0.577,  0.609)

  1    1    8    8    0  0 -1   0.250 -0.144 -0.406   0.498      0.017676555     **0.240501782**

My expected output is:

IQ JQ J_ij [meV]
1 1 0.000000000
1 6 1.846194885
1 8 0.240501782

It comes from the bold words (** **), first line is only indicative.

Advertisement

Answer

Could you please try following. Written and tested with shown examples.

awk '
BEGIN{
  print "IQ JQ J_ij [meV]"
}
FNR>1 && /IQ =/{
  value=$6 OFS $12
  found=1
  next
}
found && NF && !/ ->Q/{
  if(value){
     print value OFS $NF
  }
  value=found=""
}'  Input_file

Output will be as follows.

IQ JQ J_ij [meV]
1 1 0.000000000
1 6 1.846194885
1 8 0.240501782
Advertisement