将行首的“-from”替换为“this”

Ran*_*han 1 grep sed awk

我想在行首用“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)

什么是好的,sedawkgrep,等。

Lek*_*eyn 6

  • 当前一行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)

  • @RanaKhan - 确保将其标记为已接受的答案,以便其他人知道您的 Q 已得到解答。 (3认同)