我有文件unbound.conf
如下所示
## Simple recursive caching DNS, UDP port 53
## unbound.conf -- https://calomel.org
#
server:
access-control: 10.0.0.0/8 allow
verbosity: 1
forward-zone:
name: "."
forward-addr: 8.8.4.4 # Google
forward-addr: 8.8.8.8 # Google
forward-zone:
name: "example.com"
forward-addr: 50.116.23.211 # Open
some-other-config:
key: "value"我正在从变量(例如FORWARD_ZONES )中获取前向区域,其示例值为
forward-zone:
name: "somedns.com"
forward-addr: 1.1.1.1
forward-addr: 2.2.2.2
forward-zone:
name: "someotherdns.com"
forward-addr: 3.3.3.3
forward-addr: 4.4.4.4我需要删除conf文件中的所有前向区域,并根据接收到的输入json数组创建新的区域。
因此,在应用regex结束时,我希望有以下基于上述输入的
## Simple recursive caching DNS, UDP port 53
## unbound.conf -- https://calomel.org
#
server:
access-control: 10.0.0.0/8 allow
verbosity: 1
forward-zone:
name: "somedns.com"
forward-addr: 1.1.1.1
forward-addr: 2.2.2.2
forward-zone:
name: "someotherdns.com"
forward-addr: 3.3.3.3
forward-addr: 4.4.4.4
some-other-config:
key: "value"我应该使用什么regex来达到上述目的?
sed -i "whatShouldBeRegexStringHereThatUses_FORWARD_ZONES_variable" unbound.conf编辑:这是操场,它也展示了我做了什么,https://regex101.com/r/x0H2p3/1/
发布于 2018-03-14 07:21:49
下面这句话对我有用
sed -zri 's/(forward-zone:\s*\n\s*name: \".*\"\s*\n\s*(forward-addr: [0-9\.]*.*\s*\n\s*)+\s*\n\s*)+/$FORWARD_ZONES/' unbound.conf我需要得到一个有效的regex https://regex101.com/r/x0H2p3/2
然后用sed和
'-z'
'--null-data'
'--zero-terminated'
Treat the input as a set of lines, each terminated by a zero byte
(the ASCII 'NUL' character) instead of a newline. This option can
be used with commands like 'sort -z' and 'find -print0' to process
arbitrary file names.和
'-E'
'-r'
'--regexp-extended'
Use extended regular expressions rather than basic regular
expressions. Extended regexps are those that 'egrep' accepts; they
can be clearer because they usually have fewer backslashes.
Historically this was a GNU extension, but the '-E' extension has
since been added to the POSIX standard
(http://austingroupbugs.net/view.php?id=528), so use '-E' for
portability. GNU sed has accepted '-E' as an undocumented option
for years, and *BSD seds have accepted '-E' for years as well, but
scripts that use '-E' might not port to other older systems. *Note
Extended regular expressions: ERE syntax.发布于 2018-03-13 10:51:24
我相信,awk可以通过以下方式实现这一点:
awk 'BEGIN{p=1}
/^[-a-zA-Z]*:[[:blank:]]*$/{p=1}
/^forward-zone:[[:blank:]]*$/{p=0}
(p==0&&v==0){print var;print ""; v=1}
p' var=$FORWARD_ZONES foo.conf它本质上使用变量p检查是否需要打印一行。如果它找到一个带有regex ^[-a-zA-Z]*:[[:blank:]]*$的新配置块,那么它将默认设置打印标志p=1,但是如果配置块是^forward-zone:[[:blank:]]*$,它将禁用打印。第一次禁用打印时,它将注入$FORWARD_ZONES。
如果您的前向区域位于另一个名为forward_zones.conf的文件中,则可以使用
awk 'BEGIN{p=1}
/^[-a-zA-Z]*:[[:blank:]]*$/{p=1}
/^forward-zone:[[:blank:]]*$/{while(getline line<f2){print line); p=0}
(p==0&&v==0){print ""; v=1}
p' f2=forward_zones.conf foo.confhttps://stackoverflow.com/questions/49251367
复制相似问题