使用 sed/awk 在第一个匹配模式之后编辑第二个匹配模式
Editing second match pattern after first match pattern with sed/awk
我有以下格式的文件。如何在 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
.
欢迎来到 Stack overflow Ginny。也尝试以下 awk 命令:
awk '/}/{a=""} /cell/ && =="DFT_AXA"{a=1} a && sub("G_2","I_1") 1' Input_file
EDIT1: 根据 OP 的要求,现在也添加带有解释的非单行形式解决方案。
awk '/}/{ #### Looking for } if any line is having this character, if yes then do following.
a="" #### making variable a value to NULL.
}
/cell/ && =="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.
我有以下格式的文件。如何在 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
.
欢迎来到 Stack overflow Ginny。也尝试以下 awk 命令:
awk '/}/{a=""} /cell/ && =="DFT_AXA"{a=1} a && sub("G_2","I_1") 1' Input_file
EDIT1: 根据 OP 的要求,现在也添加带有解释的非单行形式解决方案。
awk '/}/{ #### Looking for } if any line is having this character, if yes then do following.
a="" #### making variable a value to NULL.
}
/cell/ && =="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.