sed,awk.grep - 如果该行不存在,则在配置部分的末尾添加一行 [英] sed,awk.grep - add a line to the end of a configuration section if the line doesn't already exist

查看:26
本文介绍了sed,awk.grep - 如果该行不存在,则在配置部分的末尾添加一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to edit a file using sed/awk. The file is made up of several configuration sections, like this:

SECTION 1 BEGIN
some stuff
SECTION END

SECTION 2 BEGIN
some stuff
some more stuff
important line
SECTION END

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

I want to add important line to the end of SECTION 2 if it doesn't already exist, preferably as a command one liner. I've been looking at the fgrep/sed combo in this question, but I don't quite understand how to adapt it for what I need.

注意:章节中可能有空行.

Note: there may be blank lines in the sections.

非常感谢.

推荐答案

使用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'

这篇关于sed,awk.grep - 如果该行不存在,则在配置部分的末尾添加一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆