代码之家  ›  专栏  ›  技术社区  ›  Ginny

使用sed/awk编辑第一个匹配模式后的第二个匹配模式

  •  -2
  • Ginny  · 技术社区  · 9 年前

    cell = XX cell=XX .

    File.txt
    {cell DFT_AXA
    {naming A_1 A_2 A_3 A_4 A_5 B_1 B_2 B_3 C_1 C_2 C_3 D_1 D_2 D_3 D_4 D_5 D_6
    E_1 E_2 F_1 F_2 F_3 G_1 G_2 G_3 
    H_1 H_2 H_3 H_4
    }
    

    如果 cell = DFX_AXA 代替 G_2 I_1

    1 回复  |  直到 9 年前
        1
  •  0
  •   RavinderSingh13 Nikita Bakshi    9 年前

    欢迎来到Stack overflow Ginny。也可以尝试执行以下awk命令:

    awk '/}/{a=""} /cell/ && $2=="DFT_AXA"{a=1} a && sub("G_2","I_1") 1'  Input_file
    

    编辑1: 根据OP的要求,添加非线性形式的解决方案并进行解释。

    awk '/}/{                #### Looking for } if any line is having this character, if yes then do following.
    a=""                     #### making variable a value to NULL.
    }
    /cell/ && $2=="DFT_AXA"{ #### searching string cell and then checking if 2nd field is DFT_AXA, if yes then do following.
    a=1                      #### making variable a as 1.
    }
    a && sub("G_2","I_1") 1  #### checking variable a value is NOT NULL and substitute G_2 with I_1 in a line, if both conditions are true line will be edited and 1 will print the line. awk works on condition/action method. If condition is TRUE then action should be done, if NO action is given like here so default action print will happen.
    '  Input_file            #### Mentioning Input_file here.