我想使用sed / awk编辑文件。该文件由几个配置部分组成,如下所示:
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组合in this question,,但我不太明白如何根据我的需要调整它。
注意:部分中可能有空行。
非常感谢。
答案 0 :(得分: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'
答案 1 :(得分:3)
根据迈克尔的解决方案,有一个单行:
awk -vline="important line" '/^SECTION 2 BEGIN$/{f=1}f&&$0==line{f=0}f&&/^SECTION END$/{print line;f=0}1'<<EOT
SECTION 1 BEGIN
some stuff
SECTION END
SECTION 2 BEGIN
some stuff
some more stuff
SECTION END
SECTION 2 BEGIN
some stuff
some more stuff
important line
SECTION END
SECTION 3 BEGIN
oops
SECTION END
EOT
输出:
SECTION 1 BEGIN
some stuff
SECTION END
SECTION 2 BEGIN
some stuff
some more stuff
important line
SECTION END
SECTION 2 BEGIN
some stuff
some more stuff
important line
SECTION END
SECTION 3 BEGIN
oops
SECTION END