DevOps Junky DevOps Junky - 1 year ago 52
Bash Question

how to update xml file attribute with new value (add date time) in shell script?

This is my xml below

<Deployer exitOnError="true" sourceType="Repository">
<Projects projectPrefix="">
<SubProject description="" name="Ship" overwrite="false" type="Repository">
</SubProject>
</Projects>
</Deployer>


I want o change name="Ship" to name="Ship"+currentdatetime using shell script. Any help appreciated.

I want to use sed or awk preferably (I dont want xmlstarlet as I cannot have xml tool box on my linux machine)

Please find below, which I tried.

sed "/DeployerSpec>/,<Project description='' name='bstar' overwrite='false' type='Repository'>" file

sed -i 's:<DeployerSpec exitOnError="true" sourceType="Repository"><Projects projectPrefix=""><Project description="" name="bstar" overwrite="false" type="Repository"></Project></Projects></DeployerSpec>:<DeployerSpec exitOnError="true" sourceType="Repository"><Projects projectPrefix=""><Project description="" name="bstar"+$(date+%x_%r) overwrite="false" type="Repository"></Project></Projects></DeployerSpec>:' sample.xml

sed -i.bak "s/<Project description='' name='bstar' overwrite='false' type='Repository'>/<Project description='' name='bstar'+$(date +%x_%r) overwrite='false' type='Repository'>/g" a.xml

Answer Source

try:

DATE=$(date)
sed 's/Ship/& '"${DATE}"'/g' Input_file

creating a variable named DATE which has current date, then simply using sed to substitute string Ship with Ship and current date.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download