sed,awk.grep - 如果该行尚不存在,请在配置节的末尾添加一行

sim*_*mon 0 linux awk grep sed

我想用sed/awk编辑一个文件.该文件由几个配置部分组成,如下所示:

SECTION 1 BEGIN
some stuff
SECTION END

SECTION 2 BEGIN
some stuff
some more stuff
important line
SECTION END
Run Code Online (Sandbox Code Playgroud)

我想添加important line到最后,SECTION 2如果它还不存在,最好作为一个命令一个班轮.我一直在看这个问题中的fgrep/sed组合,但我不太明白如何根据我的需要调整它.

注意:部分中可能有空行.

非常感谢.

Mic*_*ber 5

使用awk:

awk '
  $0 == "SECTION 2 BEGIN" { inSec2 = 1 } 
  inSec2 && $0 == "important line" { hasImportant = 1 } 
  inSec2 && $0 == "SECTION END" { 
    if (!hasImportant) { print "important line" } 
    inSec2 = 0
  }
  1'
Run Code Online (Sandbox Code Playgroud)