Issue
I have these variables:
file_path="/home/dir/file.xml"
string="<host mac='0A:00:DD:D2:00:02' name='vfp-20vr' ip='10.10.1.122'/>"
This is the content of file.xml
<network>
<name>br-ext</name>
<forward mode='route'/>
<bridge name='br-ext' stp='on' delay='0'/>
<mac address='52:54:00:9f:a0:00'/>
<ip address='10.10.1.11' netmask='255.255.255.0'>
<dhcp>
<host mac='0A:AA:FF:C1:A1:EE' name='vsrxa-1' ip='10.10.1.21'/>
<host mac='0A:AA:FF:C1:A2:EE' name='vsrxa-2' ip='10.10.1.22'/>
<host mac='0A:AA:FF:C1:B1:EE' name='vsrxb-1' ip='10.10.1.23'/>
<host mac='0A:AA:FF:C1:B2:EE' name='vsrxb-2' ip='10.10.1.24'/>
<host mac='0A:AA:FF:C1:C1:EE' name='vsrxc-1' ip='10.10.1.25'/>
<host mac='0A:AA:FF:C1:C2:EE' name='vsrxc-2' ip='10.10.1.26'/>
<host mac='0A:AA:FF:C1:D1:EE' name='vsrxd-1' ip='10.10.1.27'/>
<host mac='0A:AA:FF:C1:D2:EE' name='vsrxd-2' ip='10.10.1.28'/>
</dhcp>
</ip>
</network>
I would like to add the $string
right after the <dhcp>
flag, something like this:
...
<dhcp>
<host mac='0A:00:DD:D2:00:02' name='vfp-20vr' ip='10.10.1.122'/>
<host mac='0A:AA:FF:C1:A1:EE' name='vsrxa-1' ip='10.10.1.21'/>
...
I tried using sed "/\dhcp\/a $string $file_path"
in my bash script with no success...
Does anyone know how I can achieve this?
Solution
You are not too far:
sed -i "/<dhcp>/a \ \ \ \ \ \ ${string}" "${file_path}"
-i
to change input file/<dhcp>/
to select onlydhcp
open tag- (
\
) * 6 to indentstring
content
Result:
<network>
<name>br-ext</name>
<forward mode='route'/>
<bridge name='br-ext' stp='on' delay='0'/>
<mac address='52:54:00:9f:a0:00'/>
<ip address='10.10.1.11' netmask='255.255.255.0'>
<dhcp>
<host mac='0A:00:DD:D2:00:02' name='vfp-20vr' ip='10.10.1.122'/>
<host mac='0A:AA:FF:C1:A1:EE' name='vsrxa-1' ip='10.10.1.21'/>
<host mac='0A:AA:FF:C1:A2:EE' name='vsrxa-2' ip='10.10.1.22'/>
<host mac='0A:AA:FF:C1:B1:EE' name='vsrxb-1' ip='10.10.1.23'/>
<host mac='0A:AA:FF:C1:B2:EE' name='vsrxb-2' ip='10.10.1.24'/>
<host mac='0A:AA:FF:C1:C1:EE' name='vsrxc-1' ip='10.10.1.25'/>
<host mac='0A:AA:FF:C1:C2:EE' name='vsrxc-2' ip='10.10.1.26'/>
<host mac='0A:AA:FF:C1:D1:EE' name='vsrxd-1' ip='10.10.1.27'/>
<host mac='0A:AA:FF:C1:D2:EE' name='vsrxd-2' ip='10.10.1.28'/>
</dhcp>
</ip>
</network>
Answered By - Arnaud Valmary Answer Checked By - Timothy Miller (WPSolving Admin)