Search code examples
xmlbashjenkins-pipeline

Replace random generated resource name in the xml list in Bash to be useful Jenkins grrovy pipeline


I have an xml file to find and replace a line where there is url which is linked to where the Resource name = "java/RulesPlugin"

The issue is that sometimes the <Resource name="java/RulesPlugin" might be out of sequence and not in the first line. I was only able to find the example.co.uk if the Resource name = "java/RulesPlugin" is first in the list but I need to be able to filter where the url is with <Resource name="java/RulesPlugin" no matter the location or sequence in that file.

script :

grep -oPm1 '(?<=url="jdbc:postgresql://)[^<]+' <  test.xml | sed -r 's/^.{0}//' | sed 's/^[[:space:]]*//' |   cut -d: -f1
varurl=`grep -oPm1 '(?<=url="jdbc:postgresql://)[^<]+' <  test.xml | sed -r 's/^.{0}//' | sed 's/^[[:space:]]*//' |   cut -d: -f1`
echo "${varurl}"        
sed -i -e "0,/$varurl/ s/$varurl/newstring-replace.co.uk/g" test.xml

If the xml content with <Resource name="java/RulesPlugin" is not the first in the list but is down in the middle randomly. How can I use bash to get this same result?

 <?xml version="1.0"?>
    
    <Context>
    <Resource name="java/RulesPlugin"
          auth="Container"
          type="javax.sql.DataSource"
          driverClassName="org.postgresql.Driver"
          url="jdbc:postgresql://example.co.uk:5000/sandbox"
          user="xxxx"
          token="xxxxx"
          maxActive="100" 
          maxIdle="30" 
          maxWait="10000"
    
      />
      
      <Resource name="java/Reports"
          auth="Container"
          type="javax.sql.DataSource"
          driverClassName="org.postgresql.Driver"
          url="jdbc:postgresql://example.co.uk:5000/sandbox"
          user="xxxx"
          token="xxxxx"
          
     />
      <Resource name="java/Balancer"
          auth="Container"
          type="javax.sql.DataSource"
          driverClassName="org.postgresql.Driver"
          url="jdbc:postgresql://example.co.uk:5000/sandbox"
          user="xxxx"
          token="xxxxx"
    
     />

UPDATE: Thanks for all the answers, some do work on the local unix, but I really need xml tool to work with Jenkins pipeline.


Solution

  • This might work for you though parsing xml with sed is not a robust method.

    sed '/Resource name="java\/RulesPlugin"/,/\/>[[:blank:]]*$/{
         /\(.*url="jdbc:postgresql:\/\/\)[^:/]*/s//\1newstring-replace.co.uk/
    }' test.xml