我想在行首用“this”替换“-from”。当该行末尾有“R”且其上方的行末尾有“D”时,应该会发生这种情况。
例如对于下面显示的块:
-from XXXXXXXXXXXXXXXXX/D
-from XXXXXXXXXXXXXXXXX/R
-from XXXXXXXXXXXXXXXXX/K
-from XXXXXXXXXXXXXXXXX/L
-from XXXXXXXXXXXXXXXXX/G
-from XXXXXXXXXXXXXXXXX/R
Run Code Online (Sandbox Code Playgroud)
输出应如下所示:
-from XXXXXXXXXXXXXXXXX/D
-this XXXXXXXXXXXXXXXXX/R
-from XXXXXXXXXXXXXXXXX/K
-from XXXXXXXXXXXXXXXXX/L
-from XXXXXXXXXXXXXXXXX/G
-from XXXXXXXXXXXXXXXXX/R
Run Code Online (Sandbox Code Playgroud)
什么是好的,sed
,awk
,grep
,等。
D
结束时,
R
结束时,
-from
) 必须替换为-this
.awk
脚本:
# if the prev. line ended with D, and the current with R, replace first word
# optionally add && $1 == "-from"
has_d && /R$/ { $1 = "-this"; }
# print the current line, pretend that d is not matched yet
{ print; has_d = 0; }
# if line ends with D, set flag
/D$/ { has_d = 1; }
Run Code Online (Sandbox Code Playgroud)
一个班轮:
awk 'has_d&&/R$/{$1="-this"}{print;has_d=0}/D$/{has_d=1}' yourfile
Run Code Online (Sandbox Code Playgroud)