We help IT Professionals succeed at work.

Parse, sort and get latest value

enthuguy
enthuguy used Ask the Experts™
on
Hi Bash experts,

Trying to parse multiple xml files in a directory.
Extract an attribute value from available xml files. e.g liferay-version="20.0.1.5"
sort them and get the greatest value from the identified list. e.g "20.0.1.8" and store them in a variable

Was trying using python, but due to restriction on my work server. couldn't install additional packages, so couldn't use python.

Is it possible using sed/awk/bash or any way please.

file1.txt
<?xml version="1.0" encoding="utf-8"?>
<package date-created="26/11/2019" liferay-version="20.0.1.5" patch-version="5.0">
  <description />
  <system />
</package>

Open in new window


file2.txt
<?xml version="1.0" encoding="utf-8"?>
<package date-created="26/11/2019" liferay-version="20.0.1.6" patch-version="6.0">
  <description />
  <system />
</package>

Open in new window



file3.txt
<?xml version="1.0" encoding="utf-8"?>
<package date-created="26/11/2019" liferay-version="20.0.1.7" patch-version="7.0">
  <description />
  <system />
</package>

Open in new window


file4.txt
<?xml version="1.0" encoding="utf-8"?>
<package date-created="26/11/2019" liferay-version="20.0.1.8" patch-version="8.0">
  <description />
  <system />
</package>

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
This oneliner shoud do the trick:

lastversion=$(grep -oh 'liferay-version="[^"]*' file*.txt | sed 's/liferay-version="//' | sort -rV | head -n1)

Open in new window

Author

Commented:
this is cool :)
thanks so much for your help Pierre

Author

Commented:
Hi Pierre, another help on this one please

Once we get the latest....Is it possible to get the corresponding patch-version from the same file please
basically we are expecting "8.0"

Author

Commented:
just extended your script. May not be the correct way

lastversion=$(grep -oh 'liferay-version="[^"]*' file*.txt | sed 's/liferay-version="//' | sort -rV | head -n1); echo $lastversion
fileName=$(grep -l "$lastversion" file*.txt)
patchversion=$(grep -oh 'patch-version="[^"]*' ${fileName} | sed 's/patch-version="//' | sort -rV | head -n1); echo $patchversion 

Open in new window

Author

Commented:
sort is not required in the 2nd scenario

lastversion=$(grep -oh 'liferay-version="[^"]*' file*.txt | sed 's/liferay-version="//' | sort -rV | head -n1); echo $lastversion
fileName=$(grep -l "$lastversion" file*.txt)
patchversion=$(grep -oh 'patch-version="[^"]*' ${fileName} | sed 's/patch-version="//'); echo $patchversion 

Open in new window

Commented:
Hey enthuguy, I do not understand exactly what you want to do. Maybe you can issue a new question.