[awk] find pattern, change next two lines

Hi, hope you can help me... It seems like a straightforward problem, but I haven't had any success so far using my basic scripting and awk "skills":

I need to find a pattern /VEL/ in an input file that looks like this:

 1110SOL     OW25489   1.907   7.816  26.338 -0.4365  0.4100 -0.0736
 1110SOL    HW125490   1.890   7.829  26.435  0.3507  0.4216  0.0705
 1110SOL    HW225491   1.945   7.724  26.323  0.0656  0.6460 -0.2797
 1111VEL     OW25492   4.172   7.242   6.227  0.4897 -1.0759  0.7407
 1111SOL    HW125493   4.231   7.300   6.284 -1.1002 -0.8260  1.3902
 1111SOL    HW225494   4.076   7.266   6.243 -0.8879 -1.4622  1.1007
 1112SOL     OW25495   0.578   1.347  21.833 -0.3603 -0.4613 -0.2495
 1112SOL    HW125496   0.550   1.375  21.741 -0.2047  1.9848  0.3727
 1112SOL    HW225497   0.506   1.291  21.874 -0.7886 -0.8859 -1.5335

...and then replace the SOL in the following two lines with VEL, so it looks like this:

 1110SOL     OW25489   1.907   7.816  26.338 -0.4365  0.4100 -0.0736
 1110SOL    HW125490   1.890   7.829  26.435  0.3507  0.4216  0.0705
 1110SOL    HW225491   1.945   7.724  26.323  0.0656  0.6460 -0.2797
 1111VEL     OW25492   4.172   7.242   6.227  0.4897 -1.0759  0.7407
 1111VEL    HW125493   4.231   7.300   6.284 -1.1002 -0.8260  1.3902
 1111VEL    HW225494   4.076   7.266   6.243 -0.8879 -1.4622  1.1007
 1112SOL     OW25495   0.578   1.347  21.833 -0.3603 -0.4613 -0.2495
 1112SOL    HW125496   0.550   1.375  21.741 -0.2047  1.9848  0.3727
 1112SOL    HW225497   0.506   1.291  21.874 -0.7886 -0.8859 -1.5335

Thanks for any help.

awk '/VEL/{c=3}c-->=1{sub("SOL","VEL")}1' file
1 Like

Thanks a lot, Yoda, can you explain the syntax to me? I don't want to die stupid.

Sure.

awk '
        # Look for pattern VEL in each record
        /VEL/ {
                # if found set variable c value to 3
                c = 3
        }
        # For each subsequent records decrement variable c value by 1 and check if it is >= 1
        # This condition is to replace next 2 records as you requested
        c-- >= 1 {
                # Substitute SOL with VEL
                sub ( "SOL", "VEL")
        }
        # 1 == true, default awk operation is print the record
        1
' file
1 Like