从配置文件中删除一个块 [英] Remove a block from a config file

查看:33
本文介绍了从配置文件中删除一个块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个配置文件,该文件具有以下块布局:

I have a config file that has the following block layout:

{
  test,
  gracePeriodMinutes: "",
  silences: [
  {
"condition": "",
"silenceUntil": "XXXXXXXX",
"silenceComment": ""
 }
]
}

并且文件有多个块.

我想找出如何在沉默:["和之前"]之后删除行.我可以很容易地用sed删除包括"silences:["和]"在内的部分,但无法弄清楚如何保留它们并删除它们之间的所有内容.

I want to find out how to remove the lines AFTER "silences: [" and BEFORE "]". I can easily remove the portion include "silences: [" and "]" with sed, but could not figure out how to keep them and remove everything in between.

推荐答案

当逻辑变得更加复杂时,使用awk代替sed通常会更容易.试试:

When logic gets more complex, it is often easier to use awk instead of sed. Try:

$ awk '/\]/{f=0}; f==0{print}; /silences: \[/{f=1}' file
{
  test,
  gracePeriodMinutes: "",
  silences: [
]
}

工作方式:

awk脚本使用一个变量 f .在awk中,变量默认为零或为空.

How it works:

The awk script uses one variable f. In awk, variables default to zero or empty.

  • /\]/{f = 0}

这告诉awk每当我们到达包含] 的行时,将 f 设置为零.

This tells awk to set f to zero whenever we reach a line that contains ].

f == 0 {print}

这告诉awk如果 f 为零,则打印行.

This tells awk to print the line if f is zero.

/沉默:\ [/{f = 1}

如果当前行包含 silences:[,则这告诉awk将 f 设置为1.

If the current line includes silences: [, this tells awk to set f to one.

最后一个awk程序员经常以简洁为荣.在这种情况下,由于 {print} 是默认操作,因此我们不需要包含它:

Lastly awk programmers often pride themselves on conciseness. In this case, since {print} is the default action, we don't need to include it:

awk '/\]/{f=0}; f==0; /silences: \[/{f=1}'

或者,由于在awk规则下,零为false,我们可以将 f == 0 编写为not- f !f 并且使代码更短(提示: Jotne ):

Or, since, under awk rules, zero is false, we could write f==0 as not-f or !f and this makes the code even shorter (hat tip: Jotne):

awk '/\]/{f=0}; !f; /silences: \[/{f=1}' file

而且,由于在这种情况下没有歧义,因此我们可以省略两个分号中的第一个,并保留另一个字符:

And, since in this case there is no ambiguity, we can omit first of the two semicolons, saving another character:

awk '/\]/{f=0} !f; /silences: \[/{f=1}' file

这篇关于从配置文件中删除一个块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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