问题如下:
我有一个带有数据的xml文件,我正在寻找将其写入新文件的一小部分数据:请求缩短了内容:
代码片段if type=dhcp-client:
<deviceconfig>
<system>
<type>
<dhcp-client>
<send-hostname>yes</send-hostname>
</dhcp-client>
</type>
<hostname>Firewall</hostname>
</system>
</deviceconfig>片段如果type=static
<deviceconfig>
<system>
<type>
<static/>
</type>
<hostname>Firewall</hostname>
<permitted-ip>
<entry name="192.168.0.0/24"/>
</permitted-ip>
<ip-address>192.168.0.2</ip-address>
<netmask>255.255.255.0</netmask>
<default-gateway>192.168.0.1</default-gateway>
</system>
<network>
<interface>
<ethernet>
<entry name="ethernet1/1">
<layer3>
<ip>
<entry name="192.168.0.5/24"/>
</ip>
</layer3>
</entry>
</ethernet>
</interface>
<virtual-router>
<entry name="default">
<routing-table>
<ip>
<static-route>
<entry name="default-route">
<nexthop>
<ip-address>192.168.0.1</ip-address>
</nexthop>
<interface>ethernet1/4</interface>
<destination>0.0.0.0/0</destination>
</entry>
</static-route>
</ip>
</routing-table>
</entry>
</virtual-router>
</network>这四个相关的值在" system“标记<system></system>中是唯一的(或不存在),例如ip地址之类的东西可能会再次出现在<system></system>之外的其他地方,但我只检查系统内部的值,如果类型不是静态的,则不出现,我将其设置为dhcp-client。
如果类型为dhcp,则在文件中需要这样做:
type=dhcp-client如果类型是静态的,那么这就是我在文件中所需要的:
type=static
ip-address=192.168.0.2
default-gateway=192.168.0.1
netmask=255.255.255.0我不知道如何有效地完成这一任务,并将其集成到现有的PHP文件中(因此,要么与exec一起工作,要么只使用php )。
我也被限制在默认情况下安装在ubuntu服务器系统上并且无法使用其他软件包的工具。
PS:这实际上是整个/完整的用例,除了这两个示例之外,我不需要生成其他输出。)谢谢您的帮助或提示:)
发布于 2020-01-15 14:42:34
下面是一个bash脚本,它使用sed。
scriptname input.xml输出发送到std输出
#!/bin/bash
sed -n '{
/<hostname>/ {
# next line makes a comment out of hostname
# add a '#' to beginning of line to supress
s/\s*<hostname>\(.\+\)<\/hostname>/# \1/p #make hostname into a comment with hash
n # read next line to patern space
/<ip-address>/{ # if this line contains <ip-address>
i\type=static
s/\s\{1,\}<\(ip-address\)>\(.\+\)<\/\1>/\1=\2/p
n # read next line to patern space
# netmask
s/\s\{1,\}<\(netmask\)>\(.\+\)<\/\1>/\1=\2/p
n # read next line to patern space
# default-gateway
s/\s\{1,\}<\(default-gateway\)>\(.\+\)<\/\1>/\1=\2\n/p
n
b end # branch to end
}
/<ip-address>/ !{ # if line does not contain with <ip-address>
i\type=dhcp-client\
}
:end # end label
}
}
' $1https://unix.stackexchange.com/questions/562126
复制相似问题