user2382290
user2382290

Reputation: 111

bash scripting to update an XML element attribute based on prior value

I have an xml file that consists of strings

<server name="srv-usr--crt-Internal.vcdn--lfagent1">

and

<server name="srv-usr--crt-Internal.vcdn--lfagent2">
                                          ^^^^^^^^

I want to run a bash script, which continuously executes the xml file by changing the value in the server name i.e for the first time the values will be lfagent1 and lfagent2, the xml file is executed and then the value changes to lfagent3 and lfagent4. There should be around 500 to 1000 such iterations.

How to write a bash script for this test?

Upvotes: 0

Views: 135

Answers (2)

Charles Duffy
Charles Duffy

Reputation: 295291

This answer uses XMLStarlet for parsing and updating XML safely.

The first job is extracting the content:

filename="input.xml"
IFS=$'\n' read -r -d '' -a old_names \
  < <(xmlstarlet sel -t -m '//server/@name' -v . -n <"$filename")

Next, generating the new values. Assuming that the only numbers that exist in any name are at the end:

new_names=( )
for name in "${old_names[@]}"; do
  name_prefix=${name%%[0-9]*}
  old_number=${name#$name_prefix}
  new_number=$(( old_number + ${#old_names[@]} ))
  new_names+=( "${name_prefix}${new_number}" )
done

Finally, generating and running a command to update the XML file:

update_command=( xmlstarlet ed )
for idx in ${!new_names[@]}; do
  update_command+=(
    -u "//server[$((idx + 1))]/@name" # XPath uses 1-indexed values
    -v "${new_names[$idx]}"           # ...whereas bash arrays are 0-indexed
  )
done
tempfile=$(mktemp "$filename.XXXXXX")
"${update_command[@]}" <"$filename" >"$tempfile" && mv "$tempfile" "$filename"

Upvotes: 1

choroba
choroba

Reputation: 241758

Use proper XML tools for processing XML. For example, xsh:

open file.xml ;
for //server {
    my $x = xsh:match(@name, '^(srv-usr--crt-Internal.vcdn--lfagent)([0-9]+)$') ;
    if (2 = count($x))
        set @name concat($x[1], 2+$x[2]) ;
}
save :b ;

Upvotes: 1

Related Questions