Text Processing – How to Alter the Next Line After a Pattern Match Using awk

awktext processing

I have a file with lines such as:

....
pattern1 100 200 300
pattern2 300 400 400
pattern1 300 900 700
pattern1 200 500 900
...

As shown in the above example, there are some lines where pattern2 follows pattern1 but not all. I would like to match pattern1 then check if the next line has pattern2 and if it does, alter the next number field by multiplying it with a constant factor. I tried using getline with awk but it erases the lines with pattern1 from the resulting output:

awk '/pattern1/{getline; if($1==pattern2) $(NF-2)*=0.889848406214}1' infile.dat

Any suggestions how can I accomplish this without altering anything else in the input file.

Best Answer

awk '
  /pattern1/ { f = 1; print; next }
  f && /pattern2/ { $(NF-2) *= 0.889848406214 }
  { f = 0; print }
' <file
Related Question