Knowledge Base

Preserving for the future: Shell scripts, AoC, and more

Awk: compare version strings

When I was working on my dpkg for notepad++, I discovered that the naming convention changed for the release assets. So starting with version 7.9, the filenames include ".portable" instead of ".bin." I don't care about the change, but I need my automatic downloader to handle it. So, I had to add some logic for checking if the requested version number is greater than or equal to 7.9. But there is another layer of sub- version to deal with, because I know the previous release was 7.8.9. So I whipped up some awk to help me.

echo "7.8.9" | awk -v 'maxsections=3' -F'.' 'NF < maxsections {printf("%s",$0);for(i=NF;i<maxsections;i++)printf("%s",".0");printf("\n")} NF >= maxsections {print}' | awk -v 'maxdigits=2' -F'.' '{print $1*10^(maxdigits*2)+$2*10^(maxdigits)+$3}'

The output will look like:

70809

Which can then just be compared as a number with 70900 and then I can use the new naming convention. The tunables in this snippet include the awk variables: maxsections, and maxdigits. If the input version strings were to contain large numbers, such as "7.20.5" or "6028.423.2143" then you can increase the maxdigits. I realize that the second awk statement only handles a hard-coded amount of 3 sections. I need to figure out how to improve it so it can dynamically handle the number of sections defined in "maxsections" and handle the output when the maxsections is lower than the amount of fields being printed.

Comments