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

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

我想在行首用“this”替换“-from”。当该行末尾有“R”并且其上方的行末尾有“D”时,应该会发生这种情况。

例如下面所示的块:

-from XXXXXXXXXXXXXXXXX/D   
-from XXXXXXXXXXXXXXXXX/R   
-from XXXXXXXXXXXXXXXXX/K   
-from XXXXXXXXXXXXXXXXX/L   
-from XXXXXXXXXXXXXXXXX/G   
-from XXXXXXXXXXXXXXXXX/R 

输出应如下所示:

-from XXXXXXXXXXXXXXXXX/D   
-this XXXXXXXXXXXXXXXXX/R   
-from XXXXXXXXXXXXXXXXX/K   
-from XXXXXXXXXXXXXXXXX/L   
-from XXXXXXXXXXXXXXXXX/G   
-from XXXXXXXXXXXXXXXXX/R  

一切都好sed,,,,awk等等grep

答案1

  • 当上一行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; }

一班轮:

awk 'has_d&&/R$/{$1="-this"}{print;has_d=0}/D$/{has_d=1}' yourfile

答案2

sed

sed '/D$/{N;/R$/s/\n-from/\n-this/}' your_file

扩展评论:

sed ' /D$/{                          # If the current line ends in D
            N;                       # Append the next line to the pattern space
            /R$/s/\n-from/\n-this/   # If you find R at end-of-line, substitute
      }' your_file

相关内容